0
我想用指针来获取父进程与它的子进程的PID:为什么我的测试代码中的parentPid是0x1?
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
一定有什么错我的代码,任何想法?
感谢您的快速回复,现在对我有意义,所以* parentPid在每个进程中也有2个副本,在父进程中修改*父进程,并不与*父进程无关,所以*孩子的父母输出错误的值。我对吗? +1指出'getppid'函数 – mko 2012-08-08 02:44:37
@yozloy:是的,没错。孩子和父母实际上分享他们的记忆,但通过操作系统的魔力,他们的行为就好像他们不分享他们的记忆。 (通过一个称为[复制写入](http://en.wikipedia.org/wiki/Copy-on-write)的功能。)这给了两个世界的最好 - 你没有一切的两个副本,但父母和孩子不会互相obl obl。 (想象一下,如果一个对象在孩子中被释放,并且这个记忆被重新分配,这将会无情地腐蚀父母。) – 2012-08-08 02:47:49
这真的有些神奇,现在我只是坚持我的方式,我会读'copy后来写了',因为对于像我这样的新手来说,它开始为魔法疯狂起来 – mko 2012-08-08 02:59:20