#include <stdio.h>
#include <stdlib.h>
int main()
{
int n = 1;
if(fork()) // father process
{
n += 2;
printf("This is the father process%d, pid=%d\n", n, getpid());
exit(0);
// while(n++ < 10)
// sleep(1);
// printf("father exited n=%d\n", n);
}
else // child process
{
n += 5;
printf("This is the child process%d, pid=%d\n", n, getpid());
while(1)
sleep(2);
// exit(0); // 结束当前进程, 即子进程, 不会结束父进程
}
// 以下为父子进程共用的代码
printf("n = %d, pid=%d, ppid=%d\n", n, getpid(), getppid());
return 0;
}
/*
结论:
1. exit只会结束当前进程,不会结束父进程(也不会结束子进程)
2. 若父进程在子进程之前结束了, 则子进程的父进程将变为init进程(pid=1), 即保证所有进程都有父进程
3. fork()之后, 无区分父子进程的代码是父子进程共用的, 都会被执行
*/
exit会结束当前进程。但是会结束父进程和子进程吗?
最新推荐文章于 2023-03-29 22:08:54 发布