Chapter Contents |
Previous |
Next |
fork |
Portability: | POSIX.1 conforming, UNIX compatible |
SYNOPSIS | |
DESCRIPTION | |
RETURN VALUE | |
CAUTION | |
EXAMPLE | |
Output | |
RELATED FUNCTIONS |
SYNOPSIS |
#include <sys/types.h> #include <unistd.h> pid_t fork(void);
DESCRIPTION |
fork
creates a child process that duplicates the process that calls
fork
. The child process is mostly
identical to the calling process; however, it has a unique process ID. Any
open file descriptors are shared with the parent process. The child process
executes independently of the parent process.
RETURN VALUE |
fork
returns
0
to
the child process and the process ID of the child process to the parent process.
fork
returns
-1
to the parent if it is not successful and
does not create a child process.
CAUTION |
EXAMPLE |
The following example shows a program
that uses
fork
to create
a second process that communicates with the parent process with a pipe. Both
processes send messages to the terminal. The
kill
function is used by the child process to terminate both the child
and the parent.
#include <sys/types.h> #include <unistd.h> #include <string.h> #include <signal.h> #include <stdio.h> main() { int pipefd[2]; char buf[60]; int l; sigset_t shield; pid_t mypid; pipe(pipefd); if (fork()) { sigemptyset(&shield); sigaddset(&shield, SIGTERM); sigprocmask(SIG_BLOCK, &shield, 0); mypid = getpid(); for(;;) { printf("%x: What should I give my true love?\\n", mypid); l = read(0, buf, 59); buf[l-1] = 0; write(pipefd[1], buf, l); printf("%x: I gave my true love a%s %s.\\n", mypid, strchr("aeiou", buf[0])? "n": "", buf); if (strstr(buf, "poison") == buf) { printf("%x: Oh! The shame!\\n", mypid); sleep(1); break; } sleep(1); } sigprocmask(SIG_UNBLOCK, &shield, 0); sleep(10); kill(mypid, SIGABRT); } else { mypid = getpid(); for(;;) { char ch; int i = 0; do { l = read(pipefd[0], &ch, 1); buf[i++] = ch; } while(l == 1 && ch); printf("%x: My true love gave me a%s %s!\\n", mypid, strchr("aeiou", buf[0])? "n": "", buf); if (strstr(buf, "poison") != buf) { printf("%x: How sweet!\\n", mypid); } else { printf("%x: Oh, yuck!\\n", mypid); kill(getppid(), SIGTERM); printf("%x: Die, oh unfaithful one!\\n", mypid); kill(mypid, SIGABRT); } } } return(255); }
Here is a possible terminal transcript from this example program:
131073: What should I give my true love? cherry 131073: I gave my true love a cherry. 131073: What should I give my true love! 262148: My true love gave me a cherry! 262148: How sweet! poison pomegranate 131073: I gave my true love a poison pomegranate. 131073: Oh! The shame! 262148: My true love gave me a poison pomegranate! 262148: Oh, yuck! 262148: Die, oh unfaithful one! 131073 [15] Terminated
RELATED FUNCTIONS |
atfork
,
ATTACH
,
exec
,
popen
,
system
Chapter Contents |
Previous |
Next |
Top of Page |
Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.