0

我想使用指针来获取父进程的pid及其子进程:

int main(void){
  pid_t childPid,*parentPid,pid;
  childPid = fork();
  if(childPid == 0 ){
    printf("[Child] the parent pid is 0x%u\n", *parentPid);
  }else if(childPid < 0){
    printf("there is something wrong");
  }else{
    pid = getpid();
    printf("[Parent] the pid is 0x%u\n",pid);
    parentPid = &pid;
  }
  return (EXIT_SUCCESS);
}

输出是:

[Parent] the pid is 0x5756
[Child] the parent pid is 0x1

我的代码一定有问题,知道吗?

4

1 回答 1

2

孩子从不修改*parentPid,所以它只包含随机垃圾。如果您想要您的父 PID,请调用getppid.

即使您修复了竞争条件,代码仍然无法正常工作。除非共享内存,否则更改父项中的内存不会更改子项中的内存。如果默认共享所有内存,孩子和父母会立即抹掉彼此的数据并导致完全混乱。

于 2012-08-08T02:29:45.270 回答