我寫了一個使用多個管道模擬shell的C程序。問題是我可以運行大部分命令,如ls | cat
等,但我無法使用ls | wc
。 wc
不能正常工作嗎?ls |使用C的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程序中調用此命令時,您遇到此問題嗎?怎麼了? – Levon
是的,在C程序中。什麼都不會發生,'execvp()'不會返回任何錯誤。 – green
你能展示一些代碼嗎? – cnicutar