This stuff can get a little complicated but here goes.
In the parent,
fork returns the process id (PID) of the child (a number between 1 and 30,000 inclusive), and in the child,
fork returns zero:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
void main (void)
{
if (fork () == 0)
(void) fprintf (stdout, "this is the child\n");
else
(void) fprintf (stdout, "this is the parent\n");
exit (EXIT_SUCCESS);
}
Executing this returns, on my system (and most likely on yours)
Code:
this is the parent
this is the child
The parent come out first, then the child, but you're not guaranteed that will be true for every UNIX/Linux system (compile the above and run it to see).
You can control the execution of child processes by calling
wait in the parent;
wait forces the parent to suspend execution until the child is finished:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <sys/types.h>
void main (void)
{
if (fork () == 0)
(void) fprintf (stdout, "this is the child\n");
else {
(void) wait ((int *) NULL);
(void) fprintf (stdout, "this is the parent\n");
}
exit (EXIT_SUCCESS);
}
When executed,
Code:
this is the child
this is the parent
Note that
wait takes an integer pointer as an argument; the exit status of the child is placed in the location the argument points to. If a null pointer is supplied, as in the above, the exit status is not stored.
The following may be overkill, but provides a look at how to use
fork and
exec.
Where
fork becomes extremely handy is using the
exec routines, usually called after a call to
fork. The following is a simple command interpreter that uses
execlp to execute command typed by the user:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <wait.h>
#include <sys/types.h>
void main (void)
{
char line [BUFSIZ];
int process;
for ( ; ; ) {
(void) fprintf (stderr, "cmd: ");
if (gets (line) == (char *) NULL)
exit (EXIT_FAILURE);
/* create new process */
if ((process = fork ()) > 0)
(void) wait ((int *) NULL);
else if (process == 0) { /* child */
/* execute program */
(void) execlp (line, line, NULL);
/* some problem if exec returns */
(void) fprintf (stderr, "can't execute %s\n", line);
exit (errno);
} else if (process == -1) { /* can't create */
(void) fprintf (stderr, "can't fork\n");
exit (errno);
}
}
}
You compile this and execute it to type commands (like, oh,
ls or something) until you enter ^D to exit the program. Kinda cute.
Hope this helps some.