【发布时间】:2012-10-09 05:13:27
【问题描述】:
我正在研究计算机系统,我制作了这个非常简单的函数,它使用fork() 创建一个子进程。 fork() 返回一个 pid_t 如果它是一个子进程则为 0。但是在这个子进程中调用getpid() 函数会返回一个不同的、非零的pid。在我下面的代码中,newPid 是否仅在程序上下文中有意义,对操作系统没有意义?它可能只是一个相对值,根据父级的 pid 衡量吗?
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
void unixError(char* msg)
{
printf("%s: %s\n", msg, strerror(errno));
exit(0);
}
pid_t Fork()
{
pid_t pid;
if ((pid = fork()) < 0)
unixError("Fork error");
return pid;
}
int main(int argc, const char * argv[])
{
pid_t thisPid, parentPid, newPid;
int count = 0;
thisPid = getpid();
parentPid = getppid();
printf("thisPid = %d, parent pid = %d\n", thisPid, parentPid);
if ((newPid = Fork()) == 0) {
count++;
printf("I am the child. My pid is %d, my other pid is %d\n", getpid(), newPid);
exit(0);
}
printf("I am the parent. My pid is %d\n", thisPid);
return 0;
}
输出:
thisPid = 30050, parent pid = 30049
I am the parent. My pid is 30050
I am the child. My pid is 30052, my other pid is 0
最后,为什么孩子的 pid 2 比父母的高,而不是 1? main 函数的 pid 和它的 parent 之间的差是 1,但是当我们创建一个 child 时,它会增加 2 的 pid。这是为什么呢?
【问题讨论】: