日期:2014-05-16  浏览次数:20757 次

fork()的父子进程返回ID
fork()子进程返回0;父进程中,子进程向父进程返回子进程的ID这个知道了,不太明白以下这个函数的输出ID的意思
#include<stdio.h>
main(){
  fork();
  printf("get the child pid:%d\n",getpid());
  printf("get the parent pid:%d\n",getppid());
}

这个能够返回4个ID值,能够说说这4个ID值之间的关系吗?

------解决方案--------------------
UNIX环境编程关于fork这样描述的:
This function is called once but returns twice. the only difference is the returens is that the return value in the child is 0, whereas the return value in the parent is thre process ID of new child.The reason the child's precess ID is returned to the parent is that a process can have more than one child, and there is no function that allow a process to obtain the process IDs of its children.
//fork调用一次,却返回2次。子进程(即新创建的进程)返回值为0,父进程返回子进程的ID。为什么父进程返回子进程的ID呢?这是因为一个进程可以有多个子进程,然而linux没有提供函数(系统调用)获取子进程的ID。子进程可以通过getppid获取父进程的ID。
Both the child and parent continue executing with the instruction that follows the call to fork.
//父进程和子进程从fork之后的指令继续执行。