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

#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)后, 父进程才得以运行。故有以上打印。

你可能感兴趣的:(linux,code,CSAPP)