Shell implementation in C

im currently implements a shell in C. My problem occurs when I try to run a command like this:

SHELL$: sort < txtFile | grep key 

im works sort < txtFile in the process (child), and in the parent ie else if(pid > 0) im another command works to the right of the channel.

The program works fine, but it exits from the endless loop, which I set up mainly to receive input from the user.

How can I solve this problem?

this is the code that so far dealt with the pipe, I have not included the code that I have to deal with redirection:

c2p is the channel setup for me for this.

 if(pid == 0) { if( PIPE_FLAG ) { close(c2p[0]); if(dup2(c2p[1], STDOUT_FILENO) == -1){ perror("dup2() failed"); exit(2); } } /* Execute command */ execvp(cmd_args[0], cmd_args); perror("exec failed 1. "); /* return only when exec fails */ exit(-1); } else if(pid > 0) { if(PIPE_FLAG) { close(c2p[1]); if(dup2(c2p[0], STDIN_FILENO) == -1){ perror("dup2() failed"); exit(-1); } execvp(nxt_args[0], nxt_args); perror("exec failed 2. "); exit(-1); } } else { /* error occurred */ perror("fork failed"); exit(1); } 
+7
c unix shell pipe fork
source share
2 answers

I do sort < txtFile in the child process, and in the parent I run the command to the right of the channel.

What happens to your shell process? The parent process is the shell. By running the right command in the parent process, you get it to process the shell. Remember that exec () replaces the current process.

You will need fork () twice and execute the two sides of the pipe in the child processes. The parent must remain a shell that will wait () for the children to exit before presenting the next command line.

+4
source share
 /* How shell works */ #include<stdio.h> #include<unistd.h> main (int argc, char **argv) { if (argc < 2) { fprintf (stderr, "\nUsage: ./a.out cmd [options]...\n"); } if (!fork ()) { argv++; execvp (argv[0], argv); } } 
0
source share

All Articles