终结父进程,子进程变孤儿进程,孤儿进程会被init进程领养
#include <unistd.h> #include <string.h> #include <stdlib.h> #include <stdio.h> int main() { pid_t pid=fork(); if(pid<0) { printf("fork error"); exit(1); } else if(pid >0) { //父进程先打印父进程,然后终结父进程 printf("progress pid: %d, ppid: %d\n",getpid(),getppid()); exit(0); } else { //等待父进程终止,进程编程孤儿 sleep(4); printf("progress pid: %d, ppid: %d\n",getpid(),getppid()); } return 0; }
编译运行
progress pid: 16374, ppid: 1979 progress pid: 16375, ppid: 1