根据手册页
getpid() returns the process ID (PID) of the calling process.
- 在下面的代码中,为什么
parent pid
返回的值与getpid()
不同? - 主进程和父进程不一样吗?
- 为什么我在不同的系统上运行时会得到不同的输出?
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(int argc, char const *argv[])
{
printf("getpid = %d \n", (int)getpid());
pid_t pid = fork();
printf("fork returned %d \n", (int)pid);
switch (pid)
{
case -1:
perror("fork failed");
break;
case 0:
printf("I am a child with pid = %d\n", (int)pid);
break;
default:
printf("I am a parent with pid = %d\n", (int)pid);
break;
}
return 0;
}
运行时的输出:
getpid = 8208
fork returned 8209
I am a parent with pid = 8209
fork returned 0
I am a child with pid = 0
在不同的电脑上运行时的输出:
getpid = 2522
fork returned 2523
I am a parent with pid = 2522
fork returned 0
I am a child with pid = 2523
最佳答案
是的,父进程和主进程是一回事。
您的这段代码应该可以为您提供有关解决方案的线索:
switch (pid) {
/* ... */
case 0:
printf("I am a child with pid = %d\n", (int)pid);
break;
这实际上是说“如果 pid
为零,则子 pid 始终为零”。这显然不是真的,所以您对 fork()
的返回值的解释不正确。
手册页指出:
Upon successful completion, fork() returns a value of 0 to the child process and returns the process ID of the child process to the parent process.
因此变量pid
在父进程中是子进程的pid,不是父进程自己的pid.
在子进程中,您需要在 fork()
之后调用 getpid()
来获取子进程自己的 pid。
关于c - 为什么父 pid 返回的值与 getpid() 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469592/