fork()返回值bug

时间:2016-01-23 20:32:00

标签: c linux debugging fork

在下面的程序中,我在调用fork并将返回值分配给childpid时错误地引入了一个错误(第18行)。

  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <sys/types.h>
  4 #include <stdlib.h>
  5 #include <string.h>
  6
  7 int main(){
  8
  9         int     fd[2], nbytes;
 10         pid_t   childpid = -1;
 11         char    string[] = "Hello, world!";
 12         char    readbuffer[80];
 13
 14         pipe(fd);
 15         printf("Parent: Beginning of Program...\n");
 16
 17
 18         if(childpid = fork() == -1){  // BUG-FIX: Missing parenthesis (childpid=fork())==-1
 19                 printf("childpid == -1\n");
 20                 perror("fork");
 21                 exit(1);
 22         }
 23         if(childpid == 0){
 24                 // child process closes up input of pipe
 25                 close(fd[0]);
 26
 27                 // send string through output side of pipe
 28                 write(fd[1], string, (strlen(string)+1));
 29                 printf("Child %d: Finished writing to pipe!\n",childpid);
 30                 exit(0);
 31         }
 32         else{
 33                 // parent closes output side of pipe
 34                 close(fd[1]);
 35
 36                 // read in a string from the pipe
 37                 nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
 38                 printf("Parent %d: Received string: %s\n", childpid,readbuffer);
 39         }
 40
 41
 42         printf("Parent %d: End of program\n", childpid);
 43         return 0;
 44 }

错误的输出是:

$ ./a.exe
Parent: Beginning of Program...
Child 0: Finished writing to pipe!

多次运行,我注意到从未到达else块。这意味着以某种方式从未给childpid分配了值&gt;父进程内部为0。这很奇怪,因为childpid初始化为-1开始,fork确实发生了(这就是为什么childpid在子进程中得到0的原因)但是父进程&#39; childpid从未得到过值&gt; 0 - 为什么?

固定的过程是用括号括起赋值,括号输出为:

$ ./a
Parent: Beginning of Program...
Parent 106648: Received string: Hello, world!
Child 0: Finished writing to pipe!
Parent 106648: End of program

我知道修复,但我有点不清楚如何向自己解释错误代码的输出!为什么childpid会在子进程中获得0而在父进程中没有得到正值?

2 个答案:

答案 0 :(得分:3)

  if(childpid = fork() == -1){  

相当于:

  if(childpid = (fork() == -1) ){  

归因于operator precedence==(比较)的优先级高于=(赋值)。

因此childpid将在两个进程中0,除非fork()失败(在这种情况下,childpid1进程和if块永远不会被执行)。因此,永远不会执行else块。

我不是在if声明中使用作业的忠实粉丝。我更喜欢将它写在一个单独的行中,这样我就不必一直保持运算符优先级:

childpid = fork();

 if(childpid  == -1){  
   /* error */
}

if ( childpid == 0) {
  ...
}

else {
  ..
}

答案 1 :(得分:1)

在越野车版本中,你写了

    if(childpid = fork() == -1)

首先测试fork()的返回值是否为-1。通常,它不会(fork成功),因此它的计算结果为false。假值为0.然后将此0指定给childpid。该计划继续第23行:

    if(childpid == 0){

在这种情况下,childpid将始终为0,因此始终会执行此块,永远不会到达下面的 else 块。

if语句测试是否为零(false)或非零(true)。例如:

    if ( 0 ) {

是有效的语法,永远不会执行该块。另一方面,

    if ( 1 ) {

也有效,并且将始终执行。