Friday, February 29, 2008

fork and exec

When a program calls fork, a duplicate process, (called the child process) is created.The parent process continues executing the program from the point that fork was called. The child process executes the same program from the same place.

the child process is a new process and therefore has a new process ID, distinct from its parent’s process ID. The return value of fork() in the parent process is the process ID of the child.The return value in the child process is zero.

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main ()
{
pid_t child_pid;
printf ("main program process ID%d\n", (int)getpid());
child_pid = fork ();
printf ("id = %d\n:, child_pid);
if (child_pid != 0) {
printf ("
parent process,with id %d\n", (int)getpid());
printf ("
child's process ID is %d\n", (int)child_pid);
}
else
printf ("
--child process, with id %d\n", (int)getpid ());
return 0;
}
/* output:
main program process ID is 10894
id = 0
---child process, with id 10895
id = 10895
arent process, with id 10894
hilds process ID is 10895
*/


The exec functions replace the program running in a process with another program. A common pattern to run a subprogram within a program is first to fork the process and then exec the subprogram.This allows the calling program to continue execution in the parent process while the calling program is replaced by the subprogram in the child process.

No comments:

Post a Comment