Question: So I need to write a c++ code that takes two user input commands. command1 and command2. The program should then pipe, fork and then
So I need to write a c++ code that takes two user input commands.
command1 and command2. The program should then pipe, fork and then execute the commands. The user input should be treated as a unix shell command line.
for example
command1: ls
command2: wc
1 4 16
I have code that takes the first two, however, when I execute it after it takes the commands it loops the reponse back endlessly. I can not figure out what line in the code is causing it to loop forever.
Here is my code :
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
//Variables
string command1, command2;
bool quit = false;
while(quit!= true)
{
cout << "Enter your first command (including arguments) or quit to exit: ";
cin >> command1;
if(command1 == "quit")
{
quit = true;
break;
}
cout << "Enter your second command (including arguments): ";
cin >> command2;
if(command2 == "quit")
{
quit = true;
break;
}
//Create pipe
int pipefd[2];
int rs=pipe(pipefd);
//error check pipe
if(rs==-1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
//fork into two processes
rs=fork();
//error check fork
if(rs==-1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
//child process
if(rs==0)
{
//close read end of pipe, keep write end open
close(pipefd[0]);
//close standard output
close(1);
//duplicate write end of pipe into standard output
dup(pipefd[1]);
//close write end of pipe
close(pipefd[1]);
//run the first command
rs=execlp(command1.c_str(), command1.c_str(), (char*)NULL);
//error check execlp
if(rs==-1)
{
perror("execlp");
exit(EXIT_FAILURE);
}
}
//parent process
else
{
//close write end of pipe, keep read open
close(pipefd[1]);
//close standard input
close(0);
//duplicate read end of pipe into standard input
dup(pipefd[0]);
//close read end
close(pipefd[0]);
//fork into two processes
rs=fork();
//error check the fork
if(rs==1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
//child process 2
if(rs==0)
{
//run second command
rs=execlp(command2.c_str(), command2.c_str(), (char*)NULL);
//error check execlp
if(rs==-1)
{
perror("execlp");
exit(EXIT_FAILURE);
}
}
//parent process
else
{
wait(NULL);
wait(NULL);
}
}
}
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
