multiple fork - ggubuk97/apue GitHub Wiki
example 8.28
#include "apue.h"
int
main(void)
{
pid_t pid;
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid != 0) { /* parent */
printf("parent[%d] : call sleep(2)\n",getpid());
sleep(2);
printf ("parent[%d] : call exit(2)\n",getpid());
exit(2); /* terminate with exit status 2 */
}
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid != 0) { /* first child */
printf("first child[%d] : call sleep(4)\n",getpid());
sleep(4);
printf("first child[%d] : call abort()\n",getpid());
abort(); /* terminate with core dump */
}
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid != 0) { /* second child */
printf("second child[%d] : call execl \n",getpid());
execl("/bin/dd", "dd", "if=/etc/passwd", "of=/dev/null", NULL);
printf("second child[%d] : call exit\n",getpid());
exit(7); /* shouldnโt get here */
}
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid != 0) { /* third child */
printf("third child[%d] : call sleep(8)\n",getpid());
sleep(8);
printf("third child[%d] : call exit(0)\n",getpid());
exit(0); /* normal exit */
}
printf("fourth child[%d] : call sleep(6)\n",getpid());
sleep(6); /* fourth child */
printf("fourth child[%d] : call kill\n",getpid());
kill(getpid(), SIGKILL); /* terminate w/signal, no core dump */
printf("fourth child[%d] : call exit(6)\n",getpid());
exit(6); /* shouldnโt get here */
}
์คํ ๊ฒฐ๊ณผ
$ ./8.28.out
parent[4510] : call sleep(2)
first child[4511] : call sleep(4)
second child[4512] : call execl
third child[4513] : call sleep(8)
fourth child[4514] : call sleep(6)
11+1 records in
11+1 records out
5925 bytes transferred in 0.000037 secs (160330653 bytes/sec)
parent[4510] : call exit(2)
$ first child[4511] : call abort() <- parent๊ฐ ์ข
๋ฃ ๋ ๋ค์ ์๋ก ๋์๊ฐ๊ฒ ๋๋
child๋ ์์ง ๋ช
๋ น์ ์ํ ํ๊ณ ์์ผ๋ฏ๋ก ์๋ ๋ก๊ทธ๊ฐ ๋ฐ์ํ๊ฒ ๋๋ค.
fourth child[4514] : call kill
third child[4513] : call exit(0)
$