我正在研究计算机系统,我制作了这个非常简单的函数,它使用 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
最后,为什么 child 的 pid 2 比 parent 的高,而不是 1? main 函数的 pid 和它的 parent 之间的差是 1,但是当我们创建一个 child 时,它会增加 2 的 pid。这是为什么呢?
最佳答案
来自 fork man页面:
Return Value
On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.
Fork 不返回子进程的 pid,只在父进程中返回。因此,子进程没有两个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 teh child. My pid is %d\n", getpid());
exit(0);
}
else
printf("I am the parent. My pid is %d, my child pid is %d\n", thisPid, newPid);
return 0;
}
关于一个进程可以有两个PID吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12959843/