您的位置:首页 > 运维架构 > Linux

关于linux的fork用法的思考---读CSAPP

2012-11-20 15:20 295 查看
#include "apue.h"
#include <sys/wait.h>

int main(void)
{
pid_t pid;
int status;

if ((pid = fork()) < 0)
{
printf("fork error\n");
}
else if (pid == 0)
exit(7);
if (wait(&status) != pid) /* wait for child. */
printf("wait error.\n");
pr_exit(status);

if ((pid = fork()) < 0)
printf("fork error.\n");
else if (pid == 0)
abort();

if (wait(&status) != pid)
printf("wait error.\n");
pr_exit(status);
printf("-----66666--------------------------------------------------.\n");
if ((pid = fork()) < 0)
{
printf("fork error.\n");
}

else if (pid == 0)
{
printf("->>>>>>>>>>>>>>>...\n");
//		exit(0);
}
//	status /= 0;
//	printf("---77777--------------------------------------------------------.\n");
if (wait(&status) != pid)
printf("wait error.\n");
//	printf("-----------------------------------------------------------.\n");
pr_exit(status);
exit(0);
}
此时的运行结果很是为:

   normal termination, exit status = 7

abnormal termination, signal number = 6

-----66666--------------------------------------------------.

->>>>>>>>>>>>>>>...

wait error.

abnormal termination, signal number = 6

normal termination, exit status = 0

后来才明白,当我最后一次fork的时候, 没有把子进程exit后, 子进程一直运行, 之后会运行 if (wait(&status) != pid), 而他没有自己任何的子进程,故打印出 wait error. 此时staus的状态还是上一次留下来的6。此时刻, 父进程一直在wait,当子进程调用exit(0)后, 父进程才得以运行。故有以上打印。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  CSAPP LINUX CODE