gpt4 book ai didi

c - dup2、C 中的管道和 fork

转载 作者:行者123 更新时间:2023-11-30 18:00:19 25 4
gpt4 key购买 nike

我应该实现一个程序来模拟“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);
}

程序在“输入child”后卡住了,我真的不明白为什么child dup2调用没有完成......

预先感谢您的帮助。

最佳答案

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

对于功课,你需要做什么取决于你的教授。如果是这种情况,请将其标记为家庭作业。

关于c - dup2、C 中的管道和 fork ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10649407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com