我正在寫一個簡單的管道程序會要求兩個命令,然後運行程序,就好像他們進入bash作爲cmd1 | cmd2
。然後它應該循環並再次詢問,直到其中一個命令是quit
。等待(NULL)似乎會導致孩子停止執行
我已經寫了這麼多:
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/wait.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<signal.h>
using namespace std;
int main(int argc, char *argv[])
{
int pid1, pid2, errchk;
int pip[2];
char cmd1[128];
char cmd2[128];
int i = 0;
int status;
errchk = pipe(pip);//make pipe
if(errchk == -1)//check for error in pipe
{
perror("pipe");
exit(1);
}
while(i<3)
{
i++;
//Enter commands here
cout<<"Enter cmd1: ";
cin>>cmd1;
cout<<"Enter cmd2: ";
cin>>cmd2;
//if a command is quit... quit
if(strcmp(cmd1,"quit")==0 || strcmp(cmd2,"quit") == 0)
{
cout<<"Quitting...\n";
exit(1);
}
pid1 = fork();
cout<<"first fork makes pids: "<<pid1<<endl;
if(pid1 < 0)
{
perror("fork");
exit(1);
}
else if(pid1 == 0) //MAIN CHILD
{
cout<<"In main child with pid: "<<pid1<<endl;
pid2 = fork();
cout<<"second fork makes pids: "<<pid2<<endl;
if(pid2 == 0)//SUB CHILD 2 to run cmd2
{
cout<<"In child of second fork"<<endl;
close(0);
close(pip[1]);
dup(pip[0]);
execvp(cmd2,argv);//execute command2 and die
}
else if(pid2 > 0)//SUB CHILD 1 to run cmd1
{
cout<<"In parent of second fork"<<endl;
close(1);
close(pip[0]);
dup(pip[1]);
execvp(cmd1,argv);//execute command1 and die
}
}
else if(pid1 > 0) //MAIN PARENT
{
wait(NULL);//wait for cmd1
wait(NULL);//wait for cmd2
cout<<"DONE executing"<<endl; //keep going
}
}
return 0;
}
當我運行它,並進入ls
和wc
我得到的輸出是:
Enter cmd1: ls
Enter cmd2: wc
first fork makes pids: 5785
first fork makes pids: 0
In main child with pid: 0
second fork makes pids: 5786
In parent of second fork
second fork makes pids: 0
In child of second fork
DONE executing
5 5 54
我的主要問題是,我應後ls|wc
而不是其他的方式都Done executing
來。 我想了wait(NULL)
不工作,但我不知道。
請指教。 並謝謝。
你不能等待孫子。 child1必須等待的child2 –
該行'CIN >> CMD1;'和'CIN >> CMD2;'可以溢出陣列如果惡意用戶類型足夠長的字符串,不空格,導致未定義行爲。這是C++,所以請使用'std :: string',而不是'char [128]'。 – aschepler
我必須使用char,因爲execvp不能使用字符串。 – sshulgan