Prev | Current Page 1357 | Next

Christopher Negus

"Linux Bible, 2008 Edition: Boot up to Ubuntu, Fedora, KNOPPIX, Debian, openSUSE, and 11 Other Distributions"


When a process calls the fork() system call, it creates an exact copy of itself. After being created
by the fork() call, the child process typically calls one of a family of functions collectively known
as exec(), providing a program to execute and any options or arguments to that program.
Listing 28-1 illustrates the fork()/exec() process in a short program in the C language.
Actually, the child process created when a process calls a fork(), isn??™t an exact duplicate
of the parent. The process ID (PID) of the child process is different, as is the parent
PID (PPID); any file locks held by the parent are reset, and any signals pending for the parent are
cleared in the child.
LISTING 28-1
Simple fork() and exec() Sequence
/*
* forkexec.c - illustrate simple fork/exec usage
*/
#include
#include
#include
#include
int main(int argc, char *argv[])
{
pid_t child;
int status;
child = fork();
if (child == 0) {
printf("in child\n");
execl("/bin/ls", "/bin/ls", NULL);
} else {
printf("in parent\n");
waitpid(child, &status, 0);
}
return 0;
}
NOTE
752
Programming in Linux Part VI
Don??™t worry about what all the code means. The key points to understand are:
 The child = fork() statement creates a new (child) process.


Pages:
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369