gpt4 book ai didi

c - 使用 fork 和 pipe 实现管道

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:33:43 26 4
gpt4 key购买 nike

我需要使用 fork 为我的操作系统类实现无名管道,但我无法让它工作。它是一个简单的代码,没有什么特别之处,但我就是什么也没得到。我想跑ls -l | wc -l 但我每次都得到 0。

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h> // for open flags
#include <time.h> // for time measurement
#include <assert.h>
#include <errno.h>
#include <string.h>

int pid,status;
int pipefd[2];

void my_exec(char* cmd, char** argv)
{
pipe(pipefd); // Fixed
pid = fork();
// pipe(pipefd); // Original

if(pid==0){
close(pipefd[0]);
dup2(pipefd[1],fileno(stdout));
close(pipefd[1]);
execvp(cmd, argv);


}
else {
close(pipefd[1]);
dup2(pipefd[0],fileno(stdin));
while(wait(&status)!=-1);
close(pipefd[0]);
return;
}

}

int main(int argc, char** argv)
{
assert(strcmp(argv[argc-1], "-"));

int i;
for (i = 1; i < argc; ++i) {
if (!strcmp(argv[i], "-")) {
argv[i] = NULL;
my_exec(argv[1], &argv[1]);
argv = &argv[i];
argc -= i;
i = 0;
}

}

char* args[argc];
args[argc-1] = NULL;
for (i = 1; i < argc; ++i) {
args[i-1] = argv[i];

}

if (execvp(args[0], args) == -1)
perror("execvp failed");
return;
}

顺便说一句,我正在尝试的命令的输入是 ls -l - wc -l(而不是 | type -)

OK Duck 解决了它:我应该在 fork 之前创建管道,更新。

最佳答案

你最大的问题是你有一个 fork 在管道前面。这将有效地让 fork 的每个分支都调用 pipe(),因此您最终会得到两个不同的 pipefd 集,而不是同一个集。颠倒 fork() 和 pipe() 的调用顺序,然后每个 fork 中的文件描述符将相同。

作为旁注,您可以在每个 if() 语句组件中执行 printf() 调试,以确保您永远不会看到超过总共两个描述符数字。

关于c - 使用 fork 和 pipe 实现管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23111187/

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