c - getpid() 返回意外值

标签 c fork

我正在尝试运行这段 hello world 代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> 
#include <sys/types.h>

char string1[] = "\n Hello";
char string2[] = " World.\n";

int main(void)
{

int childpid;

if((childpid = fork() ) == -1){
    printf("\n Can't fork.\n"); 
    exit(0);
}

else if(childpid == 0){ /* Child process */
    printf("\n Child: My pid = %d, Parent pid = %d \n", getpid(), getppid());
    exit(0);    
}

else{ /* Parent Process */
    printf("\n Parent: Child pid = %d, My pid = %d, Parent pid = %d \n", childpid, getpid(),getppid());
    exit(0);
}

} 

关于 child 的父 PID,每次我得到的输出都是不同的:

 ~$ ./f

 Parent: Child pid = 6394, My pid = 6393, Parent pid = 27383 

 Child: My pid = 6394, Parent pid = 1842 

 ~$ ./f

 Parent: Child pid = 6398, My pid = 6397, Parent pid = 27383 

 Child: My pid = 6398, Parent pid = 6397 

查看pid = 1842属于哪个进程时发现是/sbin/upstart --user的pid。请任何人解释这些结果。

最佳答案

你有竞争条件。有时,您的 parent 完成得更快一些,当您看到这种奇怪的结果(不同的 parent ID)时就是这种情况。

在 parent 里面睡一会儿,看看会发生什么。

其实可以等你的 child :waitpid

...
int status;
waitpid(childpid, &status, 0);
printf("\n Parent: Child pid = %d, My pid = %d, Parent pid = %d \n", childpid, getpid(),getppid());
exit(0);
...

关于c - getpid() 返回意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43846901/

相关文章:

c - parent 试图读取 child 退出状态(或返回值), fork 并等待

c - 如果 getc 读取超过 4096 个字符,则会出错

将 const char* 复制到 c 中的字符串

c - 重新解释内存/指针

c - Telnet session ,fork 与 thread

c++ - 使用 Python 的 Matplotlib 绘制在 C++ 程序中生成的数据

c++ - 在广播套接字中发送私有(private) UDP 消息

c - 使用 Eclipse CDT 构建多模块 C 项目(即解决方案)

c - 将由信号更改的变量发送到子进程中由 exec 创建的进程。[C]

c - 使用 fork() 在 C 中创建两个子进程时出现问题(在 Debian 中)