在linux中,所有进程都有一个共同的父进程systemd,如果父进程退出了,子进程还没运行结束,子进程会被stsremd收养

下面用一个小程序来验证一下:

#include <cstdio>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int func(int x);

int main()
{
		pid_t pid;

		pid=fork();
		switch(pid)
		{
		case -1:
				printf("fork failed.%d:%s\n",errno,strerror(errno));
				break;
		case 0:
				printf("this is child process...\n");
				func(pid);
				break;
		default:
				printf("this is parent process...\n");
				func(pid);
				break;
		}
		return 0;
}

int func(int x)
{
		if(x==0)
		{
				for(int a=0;a<60;++a)
				{
						printf("child:a=%02d\n",a);
						sleep(1);
				}
		}
		else
		{
				for(int a=0;a<30;++a)
				{
						printf("parent:a=%02d\n",a);
						sleep(1);
				}
		}
		return 0;
}

在上面的程序中,30秒之后父进程退出,而子进程要60秒才能运行结束,看看会发生什么

编译:g++ fork.cpp -o fk

运行:./fk

父进程退出之后,子进程会发生什么?-LMLPHP

通过进程树pstree看看现象:

1、主进程还没退出

父进程退出之后,子进程会发生什么?-LMLPHP

2、主进程退出之后

父进程退出之后,子进程会发生什么?-LMLPHP

10-03 15:35