• Uncategorized

About c++ : How-to-implement-pipes-in-custom-shell

Question Detail

I am trying to implement a custom shell in linux and I am stuck on pipes implementaion by which output of a command would become input of other.
From what I have read on a website, stdin and stdout are separate for different processes.

-> Following that approach I have redirected output stdout of child process to writing end of pipe and after that I have executed ls command.

-> In the parent process, I have redirected its stdin to reading end of pipe and after that sort command has been executed(assuming it will
take input from pipe)
But the code attached below is not giving any output.
Kindly tell whats the reason.
Do I need to fork more children but why?
What if the command is ls|sort|grep “q1” ?
How would I handle if there are multiple pipes?
I have attached the code as well

#include <iostream>
#include <unistd.h>
#include <string.h>
#include <cstring>
#include <sys/types.h>
#pragma warning(disable : 4996)
using namespace std;

int main()
int fd[2];
pid_t p1;
int temp;

if(p1==0) //child
cout << "CHILD " << endl;

dup2(fd[1],STDOUT_FILENO);  //ouput directed to writing end of pipe
close (fd[1]);
execlp("/bin/ls", "/ls" ,NULL);

cout << "Parent" << endl;
dup2(fd[0],STDIN_FILENO);  //input directed to reading end
close (fd[1]);
cout <<"NOT CORRECT" << endl;

return 0;

Question Answer

No answer for now.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.