我是否了解C语言中Unix文件描述符的工作原理?

7
下面的简短程序旨在迭代从命令行传递过来的argv并执行每个参数。这不是我的作业,而是我为准备做我的作业而做的事情。
第一个参数从STDIN和STDOUT获取输入,并写入管道。在每次迭代结束时(除了最后一次),文件描述符被交换,以便由最后一个exec写入的管道将被下一个读取。通过这种方式,例如,我打算让...
./a.out /bin/pwd /usr/bin/wc 

只打印出工作目录的长度。代码如下

#include <stdio.h>                                                              
#include <unistd.h>                                                             
#include <sys/types.h>                                                          
#include <stdlib.h>                                                             
#include <string.h>                                                             

main(int argc, char * argv[]) {                                                 

  int i;
  int left[2], right[2], nbytes; /* arrays for file descriptors */

  /* pointers for swapping */
  int (* temp);
  int (* leftPipe) = left;                 
  int (* rightPipe) = right;

  pid_t childpid;                                                               
  char readbuffer[80];                                                          

  /* for the first iteration, leftPipe is STDIN */
  leftPipe[0] = STDIN_FILENO;
  leftPipe[1] = STDOUT_FILENO;

  for (i = 1; i < argc; i++) {                                                  

    /* reopen the right pipe (is this necessary?) */
    pipe(rightPipe);                                                            
    fprintf(stderr, "%d: %s\n", i, argv[i]);
    fprintf(stderr, "%d %d %d %d\n", leftPipe[0], leftPipe[1], rightPipe[0], rightPipe[1]);                                                                                    
    if ((childpid = fork()) == -1) {                                            
      perror("fork");                                                           
      exit(1);                                                                  
    }                                                                           

    if (childpid == 0) {                                                        

      /* read input from the left */                                            
      close(leftPipe[1]); /* close output */                                    
      dup2(leftPipe[0], STDIN_FILENO);                                          
      close(leftPipe[0]); /* is this necessary? A tutorial seemed to be doing this */ 

      /* write output to the right */                                           
      close(rightPipe[0]); /* close input */                                    
      dup2(rightPipe[1], STDOUT_FILENO);                                        
      close(rightPipe[1]);                                                      

      execl(argv[i], argv[i], NULL);                                            
      exit(0);                                                                  
    }                                                                           

    wait();                                                                     

    /* on all but the last iteration, swap the pipes */
    if (i + 1 < argc) {              

      /* swap the pipes */                                                      
      fprintf(stderr, "%d %d %d %d\n", leftPipe[0], leftPipe[1], rightPipe[0], rightPipe[1]);
      temp = leftPipe;                                                          
      leftPipe = rightPipe;                                                     
      rightPipe = temp;                                                         
      fprintf(stderr, "%d %d %d %d\n", leftPipe[0], leftPipe[1], rightPipe[0], rightPipe[1]);
    }                                                                           
  }                                                                             

    /* read what was last written to the right pipe */                          
    close(rightPipe[1]); /* the receiving process closes 1 */                  

    nbytes = read(rightPipe[0], readbuffer, sizeof(readbuffer));       
    readbuffer[nbytes] = 0;
    fprintf(stderr, "Received string: %s\n", readbuffer);                                

  return 0;                                                                     
}

更新: 在下面的所有测试用例中,我最初使用了/bin/wc,但 wc 揭示了厕所根本不在我想象的地方。我正在修正结果。

在一个简单的情况下(./a.out /bin/pwd),输出与预期相同:

1: /bin/pwd
Received string: /home/zeigfreid/Works/programmatical/Langara/spring_2012/OS/labs/lab02/play

运行此程序并使用第一个示例(./a.out /bin/pwd /usr/bin/wc)的输出结果为:
1: /bin/pwd
0 1 3 4
3 4 0 1
2: /bin/wc

在此时,终端会挂起(可能在等待输入)。

正如您所看到的,字符串并没有被接收到。我想象中是我在上面做了什么错误的事情,要么交换指针时出了问题,要么我不理解unix文件描述符。我的最终任务将是解释任意长度的管道,这是我解决问题的一个思路。我很难判断自己是否正确地理解了unix文件描述符。

更新:

将第二个参数设置为/bin/ls运行后,我得到了以下结果(数字是各个时间点的文件描述符):

1: /bin/pwd
0 1 3 4
0 1 3 4
3 4 0 1
2: /bin/ls
3 4 5 6
Received string: a.out
log
pipe2.c
play.c
@

这里仍然有一些垃圾,但我现在更担心自己不理解指针!这两个命令是独立的,它们并没有真正利用管道。

更新:垃圾字符是由于未关闭字符串引起的。现在我已经关闭了它,没有垃圾了。


我建议将所有的 printf(...) 调用更改为 fprintf(stderr,...)。混合使用标准 IO (printf(3)) 和较低级别的例程 (pipe(2), dup2(2), close(2)) 会带来更多麻烦,不值得冒险。 - sarnold
已经注意到了!我想 splint 会同意的。 - Ziggy
在打印字符串之前,您没有终止它,这就解释了垃圾的出现。在“读取”后尝试使用“readbytes[nbytes] = 0”。 - Niklas B.
所以,我觉得在交换之后,正在执行的进程无法从已交换的管道中读取。如果没有进行交换,我们可以从管道中读取。如果第二个进程没有从管道中读取,则它可以正常运行并将输出放入管道中。 - Ziggy
2个回答

2
挂起是由于在分叉后主进程中的“右”管道写入端没有正确关闭引起的。因此,wc永远不会停止读取(毕竟,主进程仍然可以向管道写入东西!)。只有在写入端的所有文件描述符副本都被关闭后,它才会停止读取。
这里是修复后的版本:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char * argv[])
{
  int i;
  int left[2], right[2], nbytes; /* arrays for file descriptors */

  /* pointers for swapping */
  int (* temp);
  int (* leftPipe) = left;
  int (* rightPipe) = right;

  pid_t childpid;
  char readbuffer[80];

  leftPipe[0] = STDIN_FILENO;
  // no need to assign leftPipe[1] here, it will not be used

  for (i = 1; i < argc; i++) {
    pipe(rightPipe); // create new pipe

    fprintf(stderr, "%d: %s\n", i, argv[i]);
    fprintf(stderr, "%d %d %d %d\n", leftPipe[0], leftPipe[1], rightPipe[0], rightPipe[1]);
    if ((childpid = fork()) == -1) {
      perror("fork");
      exit(1);
    }

    if (childpid == 0) {
      // use the reading end of the left pipe as STDIN
      dup2(leftPipe[0], STDIN_FILENO);
      // use the writing end of the right pipe as STDOUT
      dup2(rightPipe[1], STDOUT_FILENO);
      // close reading end of the right pipe
      close(rightPipe[0]);
      execl(argv[i], argv[i], NULL);
      exit(0);
    }
    // IMPORTANT!! close writing end of the right pipe, otherwise
    // the program will hang (this is the main bug in your original
    // implementation)
    close(rightPipe[1]);

    // wait properly!
    waitpid(childpid, NULL, 0);

    /* on all but the last iteration, swap */
    if (i + 1 < argc) {
      fprintf(stderr, "%d %d %d %d\n", leftPipe[0], leftPipe[1], rightPipe[0], rightPipe[1]);
      temp = leftPipe;
      leftPipe = rightPipe;
      rightPipe = temp;
      fprintf(stderr, "%d %d %d %d\n", leftPipe[0], leftPipe[1], rightPipe[0], rightPipe[1]);
    }
  }

  nbytes = read(rightPipe[0], readbuffer, sizeof(readbuffer));
  readbuffer[nbytes] = 0;
  fprintf(stderr, "Received string: %s\n", readbuffer);

  return 0;
}

输出:

 >> ./a.out /bin/ls /bin/cat /usr/bin/wc
1: /bin/ls
0 32767 3 4
0 32767 3 4
3 4 0 32767
2: /bin/cat
3 4 4 5
3 4 4 5
4 5 3 4
3: /usr/bin/wc
4 5 5 6
Received string:     266     294    4280

如果您对此解决方案有任何具体问题,请让我知道 :) 还有一些关于您原始代码的小问题:
  • 使用指针是不必要的,我们可以直接复制管道(性能肯定不会有问题 ;)
  • 使用了int而不是size_t
  • 您没有修复所有在使用-Wall标志编译时将呈现给您的警告

如果您感兴趣,这就是我的写法:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv) {
  size_t i, nbytes;
  int left[2], right[2], tmp[2];
  pid_t childpid;
  char readbuffer[80];

  left[0] = STDIN_FILENO;

  for (i = 1; i < argc; ++i) {
    pipe(right);

    switch ((childpid = fork())) {
      case -1:
        perror("fork");
        exit(1);
      case 0:
        dup2(left[0], STDIN_FILENO);
        dup2(right[1], STDOUT_FILENO);
        close(right[0]);
        execl(argv[i], argv[i], NULL);
      default:
        close(right[1]);
        waitpid(childpid, NULL, 0);
    }

    if (i == argc - 1) break;
    memcpy(tmp,   left,  sizeof tmp);
    memcpy(left,  right, sizeof left);
    memcpy(right, tmp,   sizeof right);
  }

  nbytes = read(right[0], readbuffer, sizeof readbuffer);
  readbuffer[nbytes] = 0;
  fprintf(stderr, "Received string: %s\n", readbuffer);

  return 0;
}

太好了!我没有使用-Wall编译,你是对的。通常我会这样做,并且我也会修复splint-weak警告,但这只是一个实验,所以我没有那么仔细。很高兴看到答案是相对较小的问题,而不是我担心的分类错误。所以答案是“是”,但我需要更多关于细节的练习。非常感谢,你的解决方案非常好! - Ziggy
@Ziggy:如果这个回答对你有帮助,欢迎接受它 :) - Niklas B.
当然会的!我倾向于这样做 :) - Ziggy

0
为了修复输出末尾的垃圾内容,请在最终的 printf 之前添加以下行。
readbuffer[nbytes] = 0;

关于挂起的问题 - 我需要更多的思考来解决。我猜测这可能与管道和缓冲有关。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接