【问题标题】:Can't read and print pipe content (from child executing through execv)无法读取和打印管道内容(从通过 execv 执行的子进程)
【发布时间】:2021-03-24 19:22:09
【问题描述】:

我编写了一个程序来读取 bash 文件并执行该文件中的命令。我得到了执行部分的工作,但我似乎无法将命令输出重定向到管道,然后从管道中读取并打印其内容。我已经阅读了有关该主题的一些主题,但解决方案似乎不起作用。这是代码,

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

 int pipefd[2];
 char buf[1024];
 int bytes = 0;

 for (int i = 1; i < argc; i++) { // reading file as argument one at a time
   FILE * fp;
   fp = fopen(argv[i], "r");
   char * buffer = NULL;
   size_t buf_size = 0;
   char bufread[1024];
   int bytes_read = 0;

   while (getline( & buffer, &buf_size, fp) != EOF) {

       pid_t pid;
       pid = fork();

       pipe(pipefd);

       if (pid == 0) {
         close(pipefd[0]);
         dup2(pipefd[1], 1);
         dup2(pipefd[1], 2);
         close(pfd[1]);

         int length = countWords(buffer);

         char * init_argv[length + 2];
         init_argv[0] = "sh";
         init_argv[1] = "-c";
         init_argv[2] = buffer;
         init_argv[3] = NULL;

         execv("/bin/bash", init_argv);
       } else {

         int status;
         close(pfd[1]);
         waitpid(pid, & status, 0);

         while (read(pfd[0], bufread, sizeof(bufread)) != 0) {
           fprintf(stdout, "%s\n", bufread);
         }
       }

     }
   }
 }

 return 0;

}

为什么当这个程序使用包含命令作为参数的有效文件运行时没有任何输出?我知道没有 dup2 和 close 指令,程序会执行命令,所以这不是问题。一旦我将 dup2 和 close 指令添加到程序中,我就无法再调试它(它在 execv 处崩溃)。

【问题讨论】:

    标签: c pipe execv


    【解决方案1】:

    我不确定这是否是问题所在,但不应该在调用fork 之前执行调用pipe(pipefd); 吗?

    就像现在一样,我认为父母和孩子各自创建了一个不同的管道,如果您想要这样做,他们不能使用这些管道相互通信。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-03
      • 1970-01-01
      • 2021-05-16
      • 2013-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      相关资源
      最近更新 更多