-
Notifications
You must be signed in to change notification settings - Fork 2
multiple fork
flowergom edited this page Oct 27, 2015
·
1 revision
#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)
$