pid_t Fork(void)
{
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork error: %s/n", strerror(errno));
exit(0);
}
return pid;
}
#ifndef __CSAPP_BASIC_H
#define __CSAPP_BASIC_H
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
/* function definition concerned with basic.c */
pid_t Fork();
#endif
#include "basic.h"
int main()
{
int pid = Fork();
int x = 2;
if (pid == 0) {
printf("child: pid = %d, ppid = %d, x = %d/n", getpid(), getppid(), ++x);
sleep(3);
printf("child: pid = %d, ppid = %d, x = %d/n", getpid(), getppid(), ++x);
exit(0);
}
printf("parent: pid = %d, ppid = %d, x = %d/n", getpid(), getppid(), --x);
}
通過 gcc fork.c basic.c -o fork 編譯即可的 fork 程序。 運行 ./fork
可以看出父進程首先退出,退出前child的PPID為12256, 退出后子進程的PPID變為了 1.說明父進程退出后的子進程由 init 超級進程1領養。而該進程是不絕不會退出的。
新聞熱點
疑難解答
圖片精選