【问题标题】:dup2, pipe and fork in Cdup2,C 中的管道和叉子
【发布时间】: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


【解决方案1】:

是否有理由不使用 dirent 列出文件 - opendir readdir 等等?或者这是学校的作业?如果它用于生产,请考虑使用 dirent.h 和 stat.h。

对于功课,您需要做什么取决于您的教授。如果是这样,请将其标记为作业。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-20
    • 2017-07-07
    • 2016-02-26
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多