【发布时间】:2023-04-01 22:40:01
【问题描述】:
我编写了一个 C 程序,它使用多个管道来模拟 shell。问题是我可以运行大多数命令,如ls | cat 等,但我无法使用ls | wc。有没有wc不起作用的情况?
int pipefd[4];
int p1 = pipe(pipefd); // Open pipe 1
int p2 = pipe(pipefd + 2); // Open pipe 2
pid_t pid;
for(i = 0; i < n_commands; i++)
{
fflush(stdout);
pid = fork();
if(pid == 0)
{
int command_no = i;
int prev_pipe = ((command_no - 1) % 2) * 2;
int current_pipe = (command_no % 2) * 2;
// If current command is the first command, close the
// read end, else read from the last command's pipe
if(command_no == 0)
{
close(pipefd[0]);
}
else
{
dup2(pipefd[prev_pipe], 0);
close(pipefd[current_pipe]);
}
// If current command is the last command, close the
// write end, else write to the pipe
if(command_no == n_commands - 1)
{
close(pipefd[current_pipe + 1]);
}
else
{
dup2(pipefd[current_pipe + 1], 1);
}
int p = execvp(tokens[cmd_pos[command_no]], tokens + cmd_pos[command_no]);
close(pipefd[current_pipe]);
close(pipefd[prev_pipe]);
close(pipefd[prev_pipe + 1]);
close(pipefd[current_pipe + 1]);
_exit(0);
}
}
如果/usr/bin 中的程序不是管道中的第一个命令,它们似乎不会被执行。
【问题讨论】:
-
当您尝试从“shell”C 程序中调用此命令时遇到此问题?会发生什么?
-
是的,在 C 程序中。什么都没有发生,
execvp()也没有返回任何错误。 -
你能显示一些代码吗?
-
奇怪 .. 我假设您尝试过其他涉及管道的命令?这些有用吗?如果您自己尝试
ls会怎样?或者,如果您执行cat somefile | wc之类的操作 .. 只是想办法缩小问题范围。 -
请发布能重现此问题的最少资源。就像一个可以证明这个问题的最小 C 程序一样。谢谢。