【发布时间】: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也返回一个值...