先让父进程死亡,子进程的父进程会被操作系统管理
先使用gcc编译代码, 执行代码后用 ps -p <进程号> -f 查看进程
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid;
// 创建子进程
pid = fork();
if (pid == -1) {
// fork失败
perror("fork failed");
exit(EXIT_FAILURE);
}
if (pid > 0) {
// 父进程代码
printf("Parent process (PID: %d) is going to exit.\n", getpid());
// 父进程退出,子进程成为孤儿进程
sleep(15);
exit(EXIT_SUCCESS);
} else {
// 子进程代码
printf("Child process (PID: %d) will continue running.\n", getpid());
// 子进程将执行一些任务,这里我们让它休眠一段时间
sleep(30);
// 子进程任务完成,退出
printf("Child process (PID: %d) has finished its task and will exit.\n", getpid());
exit(EXIT_SUCCESS);
}
return 0;
}