While循环在fork和execvp调用后没有继续
While loop not continuing after fork and execvp calls
第一次运行我的程序后,它会正确运行,但循环不会继续。
我试着在我的函数中添加更多的叉,但似乎不起作用。
#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
派生的过程。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 函数调用中参数的顺序重要吗
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 循环后如何继续阅读
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在c++类上调用void函数
- 为什么 std::unique 不调用 std::sort?
- 调用专用模板时出错"no matching function for call to [...]"
- 选择要调用的构造函数
- C++为什么尽管我调用了void函数,它却不起作用
- 构造函数正在调用一个使用当前类类型的函数
- While循环在fork和execvp调用后没有继续
- C++98 中获取并继续调用当前类不知道的类方法的最简单方法是什么?
- 我的程序在调用"parsePacket()"后是继续运行,还是等到收到数据?
- 在调用GNUPLOT之后,如何继续执行C 代码
- C++生成器不会在抛出-捕获-继续时调用析构函数
- 为什么这个递归函数在基本情况似乎得到满足后继续被调用