C++ While循环在fork和execvp调用后不继续

C++ While循环在fork和execvp调用后不继续,c++,C++,在第一次运行我的程序后,它会正确运行,但循环不会继续 我已经尝试在我的函数中添加更多的fork,但它似乎不起作用 #include <iostream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h>

在第一次运行我的程序后,它会正确运行,但循环不会继续

我已经尝试在我的函数中添加更多的fork,但它似乎不起作用

 #include <iostream>
 #include <stdio.h>
 #include <stdlib.h> 
 #include <string.h>
 #include <unistd.h> 
 #include <sys/types.h>
 #include <sys/wait.h>

 using namespace std; 

 int main(){
int pipefd[2];
int rs;
pid_t cpid;
char* args1[256];
char* args2[256];
char cmd1[256];
char cmd2[256];
char path1[10];
char path2[10];
//starts while loop 
while(true){
//creates pipe
rs = pipe(pipefd);
if (rs < 0){
    perror("pipe");
    exit(1);
}
//gets comands from user
cout << "Command 1";
cin.getline(cmd1,256);
cout << "command 2";
cin.getline(cmd2,256);
//checks id with commands are quit
if (strcmp(cmd1,"quit") == 0)
    break;
if (strcmp(cmd2,"quit") == 0)
    break;
char *token;
token = strtok(cmd1," ");
int i=0;
//splits char arrays up
while(token != NULL){
    args1[i] = token;
    token = strtok(NULL, " ");
    i++;
}
args1[i] = NULL;
token = strtok(cmd2," ");
i = 0;
while(token != NULL){
    args2[i] = token;
    token = strtok(NULL, " ");
    i++;
}
args2[i] = NULL;
strcpy(path1,args1[0]);//copis the command to the path file
strcpy(path2,args2[0]);
//forks and creates child process
rs = fork();
if (rs == 0){//child process
    close(pipefd[1]);//close write end of pipe
    close(0);//close standard input
    dup(pipefd[0]);//duplicate read end of pipe into standard 
  input
    close(pipefd[0]);//close read end of pipe
    rs = execvp(path2,args2);//runs program 2
    if (rs < 0){
        perror("execl");
        exit(1);
    }
}
else{//PARENT PROCESS
    close(pipefd[0]);//close read end of pipe
    close(1);//close standard input
    dup(pipefd[1]);//duplicate write end of pipe into standard 
   input
    close(pipefd[1]);//clsoe write end of pipe
    rs = execvp(path1,args1);//runs command 1
    if (rs < 0){
        perror("execl");
        exit(1);
    }
    }

}
return 0;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main(){
int-pipefd[2];
int-rs;
pid_t cpid;
字符*args1[256];
char*args2[256];
char-cmd1[256];
char-cmd2[256];
char-path1[10];
char-path2[10];
//在循环期间启动
while(true){
//创建管道
rs=管道(pipefd);
如果(rs<0){
佩罗(“管道”);
出口(1);
}
//从用户获取命令
库特
rs=execvp(路径1,args1);//运行命令1

“父进程”中的这一行替换当前程序。成功后不再有while循环,只有
程序1

这样想。当用户向您的程序输入
m
对命令时,您希望生成多少个进程?您希望总共有
2m
个进程,每个进程对应于一个命令,但您在当前代码中只需要fork
m
次,每个进程对应于while循环的迭代


相反,您也应该为
程序1
派生一个不同的进程,类似于您为
程序2
所做的那样。您还尝试了哪些派生?请记住
exec
函数系列完全替换当前进程,通常不会返回。它们不是
系统
的高级版本,你关于运行命令的评论也不太正确。