c中壳体的支撑管
对于一个类,我需要用C创建自己的shell。 我正在尝试使用管道支持命令管道。据我所知,管道两端都要关上。尽管如此,我还是没有得到结果,有人能发现这里出了什么问题吗 do_*函数是带有微小错误处理包装的函数。为了完整起见,它们包含在页面底部 此函数生成一个程序,并确保子级只能读取和写入正确的管道c中壳体的支撑管,c,shell,pipeline,C,Shell,Pipeline,对于一个类,我需要用C创建自己的shell。 我正在尝试使用管道支持命令管道。据我所知,管道两端都要关上。尽管如此,我还是没有得到结果,有人能发现这里出了什么问题吗 do_*函数是带有微小错误处理包装的函数。为了完整起见,它们包含在页面底部 此函数生成一个程序,并确保子级只能读取和写入正确的管道 int execute_piped_binairy (int input, int output, Pgm *program){ pid_t pid = do_fork();
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;
}
非常感谢您的帮助我自己解决了。分叉时,子对象从其父对象接收管道两端的副本。由于孩子们只闭合他们使用的端部,所以管道的一个写入端总是不闭合的。这意味着永远不会发送eof消息
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