进程在有向树中构建,您只知道您的单亲 (getppid())。简而言之,fork() 在错误时返回<strong>-1</strong>,就像许多其他系统函数一样,非零值对于 fork 调用(父)的发起者了解其新子 pid 很有用。
没有什么比例子更好:
/* fork/getpid test */
#include <sys/types.h>
#include <unistd.h> /* fork(), getpid() */
#include <stdio.h>
int main(int argc, char* argv[])
{
int pid;
printf("Entry point: my pid is %d, parent pid is %d\n",
getpid(), getppid());
pid = fork();
if (pid == 0) {
printf("Child: my pid is %d, parent pid is %d\n",
getpid(), getppid());
}
else if (pid > 0) {
printf("Parent: my pid is %d, parent pid is %d, my child pid is %d\n",
getpid(), getppid(), pid);
}
else {
printf("Parent: oops! can not create a child (my pid is %d)\n",
getpid());
}
return 0;
}
结果(在这种情况下,bash 是 pid 2249):
Entry point: my pid is 16051, parent pid is 2249
Parent: my pid is 16051, parent pid is 2249, my child pid is 16052
Child: my pid is 16052, parent pid is 16051
如果您需要在父子之间共享一些资源(文件、父 pid 等),请查看 clone()(对于 GNU C 库,也许还有其他)