#include <sys/types.h> #include <unistd.h> pid_t fork(void);
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.
Note: For a more complete description of the realationships between the parent process and the child process, see the POSIX 1003.1 standard.
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.
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); }
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
atfork
,
ATTACH
, exec
, popen
, system
Copyright (c) 1998 SAS Institute Inc. Cary, NC, USA. All rights reserved.