Hi,
I am trying to implement pipes in my own unix shell. Below is the code.
Code:
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "scanner.h"
int main(int argc, char **argv)
{
int pipefd[2];
int pid;
printf("\n[myShell--%s]$", getenv("PWD"));
while(1)
{
char *cat_args[] = {"cat", "f1", NULL};
char *wc_args[] = {"wc", "-l", NULL};
int pid1, status;
// make a pipe (fds go in pipefd[0] and pipefd[1])
pipe(pipefd);
pid1 = fork();
if(pid1 == 0)
{
pid = fork();
if (pid == 0)
{
// replace standard input with input part of pipe
dup2(pipefd[0], 0);
// close unused hald of pipe
close(pipefd[1]);
// execute wc
execvp("wc", wc_args);
}
else
{
// replace standard output with output part of pipe
dup2(pipefd[1], 1);
// close unused unput half of pipe
close(pipefd[0]);
// execute cat
execvp("cat", cat_args);
}
}
else
{
wait(NULL);
printf("[myShell--%s]$", getenv("PWD"));
}
}
}
I want to execute the command and go back to my own prompt. But instead it goes on printing "[myShell]. If I remove one parent fork, then it execute fine, but exits my shell.
Thanks in advance !!