[英]Why does the pipe break out of the loop?
我正在為c開發一個shell程序,並試圖弄清楚為什么提示用戶作出響應后它仍不斷跳出循環。 它可以正確運行命令,但是由於某些原因會中斷。 我不知道為什么,我認為它必須以我做管道的方式做些事情。
這就是我的示例,應該運行管道命令,並要求用戶繼續一次又一次地運行命令,直到用戶輸入“是”以外的內容。 可能是execvp導致中斷嗎? 我怎么能擁有它,使它繼續循環? 使用分叉更新進行編輯。
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
int main()
{
char str[3];
do{
char* leftSide[] = {"ls", NULL};
char* rightSide[] = {"wc", NULL};
pid_t id, id2;
int pipe_fd[2];
pipe(pipe_fd);
id = fork();
if(id == 0){
dup2(pipe_fd[0],0);
close(pipe_fd[1]);
close(pipe_fd[0]);
if(execvp(rightSide[0], rightSide) == -1){
perror("error running pipe right command");
}
}
else{
id2 = fork();
if(id2 == 0){
dup2(pipe_fd[1],1);
close(pipe_fd[1]);
close(pipe_fd[0]);
if(execvp(leftSide[0],leftSide) == -1){
perror("error running pipe left command");
}
}
else{
wait(NULL);
wait(NULL);
}
}
printf("Continue?");
fgets(str, 3, stdin);
str[3] = '\0';
}while(strcmp(str, "yes") == 0);
return 0;
}
您正在通過以下方式終止程序
if(execvp(leftSide[0],leftSide) == -1){
您必須兩次fork()
; 一次用於rightSide
,一次用於leftSide
。
這里有兩個問題:
正如@ensc指出的那樣,在他的回答中,您的程序在調用execvp
時終止。 您將不得不生兩個孩子,父母將保留您的程序,要求用戶提供更多輸入,而孩子將執行leftside
和rightside
。
第二個問題是fgets
根據手冊頁:
fgets()最多從流中讀取小於大小的字符,並將它們存儲到s所指向的緩沖區中。 在EOF或換行符之后停止讀取。 如果讀取了換行符, 則將其存儲在buffer中 。
因此,從用戶輸入的字符串將是"yes\\n"
而不是"yes"
並且strcmp
將始終失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.