【问题标题】:Unix: Getting execl functions to read from stdinUnix:让 execl 函数从标准输入中读取
【发布时间】:2014-02-25 08:06:04
【问题描述】:

在我正在编写的 C 程序中使用“/usr/bin/sort”调用 execl 时遇到问题。对排序的调用似乎不是从标准输入读取或打印任何输出。代码如下:

// forking children, creating pipes, etc.
// ...
// These lines:

char msg[256];
read(pipe2[0], msg, 256*10);
printf("%s\n", msg);

//Produce this output:

bash-4.2/make_cmd.c:2
bash-4.2/mailcheck.h:0
bash-4.2/findcmd.c:6
bash-4.2/command.h:4
bash-4.2/config-top.h:1
bash-4.2/redir.c:2
bash-4.2/variables.c:7
bash-4.2/unwind_prot.c:0
bash-4.2/arrayfunc.h:0
bash-4.2/variables.h:0
bash-4.2/bracecomp.c:0
...

// So I know that pipe2[1] is being written to by the previous child.
// but for some reason this child will not read from pipe2[0]

   pid_3 = fork();
   if (pid_3 == 0) {
     /* Third Child */
     memset(cmdbuf, 0, BSIZE);
     dup2(pipe2[0], STDIN_FILENO);
     dup2(pipe3[1], STDOUT_FILENO);
     close(pipe2[0]);
     close(pipe3[1]);
     sprintf(cmdbuf, "/usr/bin/sort -t : +1.0 -2.0 --numeric --reverse");
     if(execl("/usr/bin/bash", "bash", "-c", cmdbuf, (char*)NULL) < 0){
        perror("Error calling sort: ");
        return(-1);
     }
     exit(0);
   } 


// and after "reading..." is printed, the program hangs instead of
// printing "parent: [whatever the output of sort would be]\n"

printf("reading...\n");
read(pipe3[0], msg, BSIZE);
printf("parent: %s\n", msg);
exit(0);

即使我将 cmdbuf 作为“-t :”传递或将调用传递给不带参数的 sort,也不会发生任何事情。我也试过直接通过排序而不像这样 /usr/bin/bash

execl("/usr/bin/sort", "sort", (char*)NULL); 

无济于事。

【问题讨论】:

  • exec.* 函数返回一个值。忽略它,后果自负。另请参阅:errno、perror。
  • 我在我的实际代码中添加了一个 if 语句来检查 exec 是否有效,还添加了 perror,感谢您的提示。但是在调用 read(pipe3[0], msg, BSIZE); 后代码仍然挂起; exec 调用没有输出或错误消息。我将这里的代码更新到当前的源代码
  • read 也返回一个值...

标签: c unix stdin pipe


【解决方案1】:

如果您是刚开始在 UNIX 中使用管道的人,那么问题就不那么明显了。

我的程序总共打开了 3 个管道。每个孩子只使用其中两个管道来路由他们的标准输入和标准输出数据。对于每个孩子,我只关闭了被复制到该孩子的标准输入和标准输出文件描述符的管道。显然这是一个禁忌,正确的做法是让每个孩子在完成调用 dup2 时关闭每个管道。来源:http://www.tldp.org/LDP/lpg/node11.html

【讨论】:

    猜你喜欢
    • 2016-03-22
    • 1970-01-01
    • 2011-11-15
    • 2016-12-13
    • 2019-07-26
    • 2013-03-30
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多