While循环在fork和execvp调用后没有继续

While loop not continuing after fork and execvp calls

本文关键字:继续 调用 execvp 循环 fork While      更新时间:2023-10-16

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

我试着在我的函数中添加更多的叉,但似乎不起作用。

#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;
}

在第一次通过循环后,应该要求用户输入另外两个命令,或者能够退出功能

rs=execvp(path1,args1(//运行命令1

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

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

您也应该为program 1派生一个不同的进程,类似于为program 2派生的过程。