对于一个类,我需要在C中创建自己的shell。 我试图使用管道支持命令管道。据我所知,管道的两端都会关闭。不过,我没有得到任何结果,有人能发现这里有什么问题吗?
do_ *函数是具有微小错误处理包装的函数。为了完整起见,它们包含在页面底部。
此函数生成一个程序,并确保子项只能读取和写入正确的管道。
int execute_piped_binairy (int input, int output, Pgm *program){
pid_t pid = do_fork();
if (pid == 0){ //I am the child
if (input != 0){//input is not standard input, overwrite stdin with given input
do_dub_and_close(input, 0);
} if (output != 1) { //output is not standard output, overwrite stdout with given output
do_dub_and_close(output, 1);
}
do_exec(program->pgmlist);
} else {
return pid;
}
}
此函数生成k个子节点和k-1个管道以执行k命令。命令以相反的顺序给出,这意味着第一个命令应该输出到全局输出。
int execute_binairy_list (int input, int output, int pgmCount, Pgm *program){
int childPids[pgmCount];
int childStatus[pgmCount];
int childId;
int idx;
// For k programs we need k-1 pipes and need to spawn k children
for(idx = 0; idx<pgmCount-1; idx++){
int file_descriptors[2]={0, 1};
//create unnamed pipe
do_pipe(file_descriptors);
// pass stored input and created write file descriptor
childId = do_execute_piped_binairy (file_descriptors[0], output, program+idx);
childPids[idx]=childId; //keep child id to make parent wait for all children.
if(output!=1){
do_close(output);
};
do_close(file_descriptors[0]); // close read end of new pipe, child reads from this pipe.
output = file_descriptors [1]; //store write end of new pipe for next iteration
}
//we still need to spawn 1 child to execute the first command based on the global input
// pass stored input and created write file descriptor
childId = do_execute_piped_binairy (input, output, program+idx);
childPids[idx]=childId; //keep child id to make parent wait for all children.
if(output!=1){
do_close(output);
};
for(idx=0; idx<pgmCount; idx++){
do_wait(childPids[idx], childStatus+idx); //wait for all children to return;
}
return 0;
}
我已经用三个命令测试了我的代码,希望这个命令会产生这样的顺序: command1 - &gt; pipe1 - &gt; command2 - &gt; pipe2 - &gt;指令代码 当使用大量printfs运行时,会发生这种情况(调度会影响订单或多或少):
created pipe: 3 4 //pipe 2
created child: 2452 //command 3
closed input: 3 //parent closes read end of pipe 2
created pipe: 3 5 //pipe 1
child: 2452 3 1 //command 3 reads from read end of pipe 2 and writes to 1
closed input: 3 2452 //command 3 closes read end of pipe 2
created child: 2453 //command 2
closed output: 4 //parent closes write end of pipe 2
closed input: 3 //parent closes read end of pipe 1
closed output: 5 //parent closes write end of pipe 1
child: 2453 3 4 //command 2 reads from read end of pipe 1 and writes to write end of pipe 2
closed input: 3 2453 //command 2 closes read end of pipe 1
closed output: 4 2453 //command 2 closes write end of pipe 2
child: 2454 0 5 //command 1 reads from 0 and writes to write end of pipe 1
closed output: 5 2454 //command 1 closes write end of pipe 1
非常感谢任何帮助
答案 0 :(得分:0)
自己想通了。分叉时,孩子们从父母那里收到管道两端的副本。由于孩子们只关闭他们使用的两端,所以总是有一个管道的写端不靠近。这意味着没有发送任何eof消息