fork-system calls
fork-system calls
SYNTAX:
The exec family of functions replaces the current running process with a new process.
It can be used to
run a C program by using another C program. It comes under the header file unistd.h.
There are many
members in the exec family which are shown below with examples.
The execlp system call duplicates the actions of the shell in searching for an
executable file if the
specified file name does not contain a slash (/) character. The search path is the path
specified in the
environment by the PATH variable. If this variable isn‟t specified, the default path
":/bin:/usr/bin" is
used.
The execlp system call can be used when the number of arguments to the new
program is known at
compile time. If the number of arguments is not known at compile time, use execvp.
SYNTAX:
#include<unistd.h>
intexeclp(constchar *file, constchar *arg, ...);
status: Status value returned to the parent process. Generally, a status value of 0.
ALGORITHM:
Step1: Start the program
Step2: Declare p
Step3: Call the fork system call for p.
Step4: If p is equal to -1 then
4.1: Print “Process creation unsuccessful”
4.2: Terminate using exit system call.
Step5: If p value is 0 then
5.1: Print “Child process starts”
5.2: Load the program in the given path into child process using exec system call.
5.3: If the return value of exec is negative then print the exception and stop.
5.4: Terminate the child process.
Step6: If p value is >0 then
6.1: Suspend parent process until child completes using wait system call
6.2: Print “Child Terminated”
6.3: Terminate the parent process.
Step7: Stop
PROGRAM
#include<unistd.h>
#include<stdio.h>
int main()
{ pid_t pid;
/* fork a child process */
pid = fork();
if (pid < 0)
{
printf(“\nfork() failed....”);
return 1;
}
else if (pid == 0)
{
/* child process */
execlp("/bin/ls", "ls", NULL); // A new program(ls executable is loaded into
memory and executed
exit(1);
}
else
{
/* parent process */
/* parent will wait for the child to complete */
wait(NULL);
printf("Child Complete");
}
return 0;
}