|
发表于 2003-6-9 08:24:37
|
显示全部楼层
还是我来解释一下吧。把源程序改成这样:
- #include <sys/wait.h>
- #include <unistd.h>
- #include <stdlib.h>
- int main()
- {
- pid_t pid;
-
- printf("pid=%d before fork()\n", getpid());
-
- if((pid=fork())<0)
- printf("fork failde!");
-
- if(pid==0)
- {
- printf("pid=%d before getpid() in child\n",pid);
- pid=getpid();
- printf("pid=%d after getpid() in child\n",pid);
- printf("pid=%d after getppid() in child\n", getppid());
- }
- else
- {
- printf("pid=%d before wait() in parent\n",pid);
- printf("getpid(): pid=%d before wait() in parent\n", getpid());
- pid=wait((int *) 0);
- printf("pid=%d after wait() in parent\n",pid);
- }
- }
复制代码
运行后的结果:
sh-2.05b$ ./a.out
pid=293 before fork()
pid=294 before wait() in parent
getpid(): pid=293 before wait() in parent
pid=0 before getpid() in child
pid=294 after getpid() in child
pid=293 after getppid() in child
pid=294 after wait() in parent
sh-2.05b$
从这个结果可以看出。楼主把fork()返回给父进程的子进程pid当成父进程的pid在printf("pid=%d before wait() in parent\n",pid);等语句中使用,如果在父进程中使用getpid(),很快就能看出两个pid不一样。 |
|