LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
楼主: colored

[c]关于fork()前后进程的运行

[复制链接]
 楼主| 发表于 2003-6-8 20:50:07 | 显示全部楼层

还有点不明白

  1.         if(pid==0)
  2.         {
  3.                 printf("pid=%d before getpid() in child\n",pid);
  4.                 pid=getpid();
  5.                 printf("pid=%d after getpid() in child\n",pid);
  6.         }
复制代码
按我理解,这段代码是子进程使用的,getpid()得到应该是子进程的id,可得到的是父进程的id :ask
发表于 2003-6-8 22:35:10 | 显示全部楼层
刚才 libinary 说了,pid==0 的时候,是父进程。
发表于 2003-6-8 23:54:49 | 显示全部楼层
在父进程中返回的是0.在子进程中返回的不是0.
所以pid==0的时候,是父进程吧?
发表于 2003-6-9 08:18:49 | 显示全部楼层
最初由 viper 发表
刚才 libinary 说了,pid==0 的时候,是父进程。

不对吧,应该是pid大于0时是父进程。pid等于0时,是子进程。这个问题是楼主概念不清,自已把自己搞糊涂了。
发表于 2003-6-9 08:19:27 | 显示全部楼层
最初由 0100 发表
在父进程中返回的是0.在子进程中返回的不是0.
所以pid==0的时候,是父进程吧?

错了,正好相反。
发表于 2003-6-9 08:24:37 | 显示全部楼层
还是我来解释一下吧。把源程序改成这样:

  1. #include <sys/wait.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>

  4. int main()
  5. {
  6.         pid_t pid;
  7.        
  8.         printf("pid=%d before fork()\n", getpid());
  9.        
  10.         if((pid=fork())<0)
  11.                 printf("fork failde!");
  12.        
  13.         if(pid==0)
  14.         {
  15.                 printf("pid=%d before getpid() in child\n",pid);
  16.                 pid=getpid();
  17.                 printf("pid=%d after getpid() in child\n",pid);
  18.                 printf("pid=%d after getppid() in child\n", getppid());
  19.         }
  20.         else
  21.         {
  22.                 printf("pid=%d before wait() in parent\n",pid);
  23.                 printf("getpid(): pid=%d before wait() in parent\n", getpid());
  24.                 pid=wait((int *) 0);
  25.                 printf("pid=%d after wait() in parent\n",pid);
  26.         }
  27. }
复制代码

运行后的结果:

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不一样。
发表于 2003-6-9 10:12:29 | 显示全部楼层
哈哈,不好意思,居然搞反了。
 楼主| 发表于 2003-6-9 19:24:26 | 显示全部楼层

我想可以这样理解

fork()返回的是子进程的ID,所以在父进程中pid为非负数,是子进程的id,
而在子进程中,没有子子进程,所以fork()返回为0。
发表于 2003-6-9 22:42:04 | 显示全部楼层
基本正确。在子进程中如果不再次fork(),是不会有子子进程的。
发表于 2003-6-10 05:14:33 | 显示全部楼层

回复: 我想可以这样理解

最初由 colored 发表
fork()返回的是子进程的ID,所以在父进程中pid为非负数,是子进程的id,
而在子进程中,没有子子进程,所以fork()返回为0。


这是 fork() 的 man 里面说的,反正 fork() 在子进程里面返回一个零,并没有说因为“子进程中,没有子子进程,所以fork()返回为0”。:p

On success, the PID of the child process is returned  in  the  parent's thread  of execution, and a 0 is returned in the child's thread of execution.  On failure, a -1 will be returned in the parent's context,  no child process will be created, and errno will be set appropriately.
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表