【发布时间】:2012-05-18 08:42:43
【问题描述】:
我应该实现一个程序来模拟“ls -l | sort -n”的行为,我已经编写了我的代码,根据我的逻辑,一切都应该正常工作,但事实并非如此。 在过去的几个小时里,我一直在尝试调试这个,所以任何额外的输入都将不胜感激。 代码如下:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
int main(int argc, char *argv[])
{
int fd[2];
int errcheck;
errcheck = pipe(fd);
printf("Errcheck after pipe call: %d\n", errcheck);
pid_t childpid;
childpid=fork();
if(childpid==0)
{
printf("Entering child\n");
errcheck = dup2(fd[1], STDOUT_FILENO);
printf("Errcheck after dup2 child: %d\n", errcheck);
close(fd[0]);
execl("bin/ls", "ls", "-l", NULL);
}
printf("Before sort call\n");
errcheck = dup2(fd[0], STDIN_FILENO);
printf("Errcheck after dup2 parent: %d\n", errcheck);
close(fd[1]);
execl("/usr/bin/sort", "sort", "-n", NULL);
}
“Entering child”后程序卡住了,我真的不明白为什么child dup2 call没有完成...
提前感谢您的帮助。
【问题讨论】:
-
bin/ls看起来像一个相对路径 -
大声笑,是的,这是我下次记得使用的技巧。非常感谢:)
-
它在@Jens 的(现已删除)答案中
-
您不想在调用
dup2(fd[1], STDOUT_FILENO)后执行printf- 您的 printf 正在写入管道。使用fprintf代替 stderr。
标签: c unix system-calls