我正在尝试创建一个简单的 shell 接口(interface)程序,该程序将 shell 命令作为来自父进程的用户输入,并通过实际执行 shell 命令的 pip IPC 将简单的 shell 命令发送到子进程。即使在输入“quit”后,子 while 循环也会继续重复
int main() {
char userInput[BUFFER_SIZE];
int fpipe[2];
pid_t pid;
// INTRODUCTION TO PROGRAM
printf("------- WELCOME TO THE FORKED PARENT -------\n");
printf("------- YOU MAY QUIT AT ANY TIME BY TYPING 'quit' or 'q' -------\n");
if (pipe(fpipe)== -1){
printf("------- PIPE HAS FAILED -------\n");
return 1;
}
pid = fork();
if (pid < 0){
printf("------- FORK HAS FAILED -------\n");
return 1;
}
if (pid > 0){
close(fpipe[0]);
printf("\nosh> ");
scanf("%s", userInput);
while ((strcmp(userInput,"quit") != 0 && strcmp(userInput,"q") != 0)){
printf("\nosh> ");
write(fpipe[1], userInput, strlen(userInput)+1);
scanf("%s", userInput);
}
close(fpipe[1]);
}
else{
close(fpipe[1]);
while(1){
if (read(fpipe[0], userInput, BUFFER_SIZE) == -1){
return 1;
}
if ((strcmp(userInput,"quit") != 0 && strcmp(userInput,"q") != 0)){
system(userInput);
printf("osh> ");
}
else{
break;
}
}
close(fpipe[0]);
}
return 0;
}
最佳答案
问题是当用户输入quit
时,父级中的循环停止,它不会将其发送给子级。因此子进程停止循环的条件永远不会匹配。它不断从管道中读取数据,但由于处于 EOF,因此它不会返回任何内容,因此它会继续执行发送的最后一个命令。
最简单的解决方案是子进程在从管道中获取 EOF 时跳出循环,而不是寻找退出
。
while(1){
int n;
n = read(fpipe[0], userInput, BUFFER_SIZE);
if (n == -1) {
return 1;
}
if (n == 0) {
break;
}
system(userInput);
}
关于c - 在 C 上使用 fork 进程失败 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60645997/