我正在尝试在 C 中实现多个管道,例如
ls - al | less | wc
我在创建管道时遇到了麻烦。我有一个循环应该创建进程并将它们与管道连接:
for(i=0;i<num_cmds;i++){
create_commands(cmds[i]);
}
我的create_commands()
功能看起来像这样
void create_commands (char cmd[MAX_CMD_LENGTH]) // Command be processed
{
int pipeid[2];
pipe(pipeid);
if (childpid = fork())
{
/* this is the parent process */
dup2(pipeid[1], 1); // dup2() the write end of the pipe to standard output.
close(pipeid[1]); // close() the write end of the pipe
//parse the command
parse_command(cmd, argvector);
// execute the command
execvp(argvector[0], argvector);
close(1); // close standard output
}
else
{
/* child process */
dup2( pipeid[0], 0); // the read end of the pipe to standard input
close( pipeid[0] ); // close() the read end of the pipe
}
}
但这不起作用,我的标准输入和标准输出搞砸了。谁能指出我做错了什么?
先感谢您!