C S C O R N E R

Example: Use of system calls, “fork()”, “wait()” and “exec()” for Linux in C

Objective:
  • To know about system calls like fork, wait, and exec
  • How to work on Ubuntu terminal
  • How to compile a program using gcc compiler and execute a program through terminal
Problem Statement:
Write a C program in any editor of Linux in which you have to create one child using fork system call. In child process, message will be displayed to take input for two tasks through Switch or If else statements.
  • One for execution of ping command for any website i.e ping yahoo.com using theexeclp() system call.
  • Second to create any directory using mkdir command i.e mkdir VU
Parent process should wait until child finishes its execution through Wait() call and display a message “Well done Kid”.
Finally Both Parent and Child ID should be displayed.
  • Save the program in your student id directory which can be created anywhere i.e Desktop
  • Attach only two screen shots i.e one for ping and other for mkdir
Solution:
  1. Using Linux (Ubuntu) to Compile code
  2. To compile command is “gcc program.c”
  3. To run program command is “./a.out”
Code:



//written by Tasaddaq Hussain
//12 May 2016
//Bc110200816@gmail.com | Virutal University of Pakistan
 
//header files
 
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
 
int main(void)
{
int pid, status, ch;            //declarations of variables
pid =fork();                         //creating process
 
if(pid == -1)                        //if process is not created
 
{
printf("Fork failed\n");
exit(1); //terminate with error
}
else if(pid ==0) //if CHILD process created, else Parent Process will be executed
{
printf("Select the choice:\n");
printf("1- For Ping\n");
printf("2- To make directory\n\n");
 
scanf("%d", &ch); //Asking for choice
 
switch(ch)
{
case 1:
//passing parameters to execlp() function to ping LMS up to 6 times
 
if(execlp("/bin/ping","ping","-c 6","vulms.vu.edu.pk",NULL)<0)
{
//if function's return value will be -1 (failed to ping) then display,
 
printf("exec failed\n");
exit(1); //terminate with error
}
break;
 
case 2:
 
//passing parameters to execlp() function to make new Directory named as "VU" in current directory
 
if(execlp("/bin/mkdir","mkdir","VU",NULL)<0)
{
//if function's return value will be -1 (failed to ping) then display,
 
printf("Exec failed");
exit(1); //terminate with error
}
break;
 
default:
printf("wrong choice");
break;
}
}
else        //after termination of CHILD this "Parent process Executed
{
wait(&status);   //wait until CHILD processes terminate
printf("\nWell Done kid!\n");
 
printf("Parent ID is : %d", getpid());         //Displaying Parent process's ID
 
printf("\nChild ID is : %d\n", pid);             //Displaying CHILD's process's ID
exit(0); //terminate normally
}
}

Screenshots:

No comments:

Powered by Blogger.