首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

一个简单的vfork pid 有关问题

2012-07-27 
一个简单的vfork pid 问题?源码:#include unistd.h#include sys/types.h#include sys/wait.h#includ

一个简单的vfork pid 问题?
源码:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <math.h>
int main()
{
 pid_t child;
 if((child=fork())==-1)
{
 printf("fork error: %d \n",strerror(errno));
 exit(1);
}
else if(child==0)//子进程
{
printf("I am the child: %d\n ",getpid());
printf("father pid id :%d\n",getppid());
exit(0);
}
else
{
printf("I am the father:%d \n ",getpid());
return 0;
}
}
运行结果:为什么有时是这样的
I am the father:3330 
 I am the child: 3331
 father pid id :1

父进程号不一致,但大不多情况下运行结果想这样:
I am the father:3366 
 I am the child: 3367
 father pid id :3366
这是为什么呢?谢谢大家!


[解决办法]
int pid = fork();
if (0 == pid)
{
printf("I am the child: %d\n ",getpid());
printf("father pid id :%d\n",getppid());
}
else
{
printf("I am the father:%d \n ",getpid());
}

I am the child: 17031
 father pid id :17030
I am the father:17030

确实是这样的,搞不懂楼主哪里来的1

[解决办法]
晕 哪来的1
[解决办法]
因为父进程比子进程先退出,于是子进程是孤儿进程,被init进程收留,而init进程就是1.

如果是第二种打印结果,那么是子进程先退出,父进程再退出,这样会导致子进程成为僵尸进程(也就是留下了一些没有回收的资源),所以请记住父进程wait.

热点排行