0

I have written a program that gets command line arguments such as ls, cat and executes them. Now I need to extend this program for i/o redirection and do shell pipes as well. Here is my program for the simple shell.

if ((pid = fork()) == -1 ) { /* error exit - fork failed */ 
    perror("Fork failed");
    exit(-1);
}
if (pid == 0) { /* this is the child */
    printf("This is the child ready to execute: %s\n",argv[1]);
    execvp(argv[1],&argv[1]);
    perror("Exec returned");
    exit(-1);
} else {
    wait(pid,0,0);
    printf("The parent is exiting now\n");
    ...
}

I don't know how to add pipes and redirection in this same program!

dup(pipeID[0]);
close(pipeID[0]);
close(pipeID[1]);
execlp(argv[3],argv[3],argv[4],0); 

I know that I have to use dup() or dup2() for redirection and pipe() too, but how do I do it all together in the same program?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

1

There are many SO questions that address some or all of these issues. The more relevant search terms in the SO search buffer are [c] [shell] (tags shell and C). Questions include:

  1. Writing my own shell in C: how do I run Unix executables?
  2. Redirecting the output of a child process?
  3. How can I implement my own basic Unix shell in C?
  4. Writing Linux shell?
  5. Shell program and pipes in C?

You can probably come up with a better selection if you try harder.


There are a number of issues you'll need to address:

  • Pipes need to be set up before the fork that creates the two processes connected by the pipe.
  • I/O Redirection can be done in the child (only).
  • You need to parse the command line to split it into command names, arguments, and I/O redirections.
  • You need to be careful to ensure that enough of the pipe file descriptors are closed (that's usually all of them by the time you're done).
  • Given a pipe line sort file1 file2 | uniq -c | sort -n, which process or processes is the parent shell going to wait for? All of them? Just the first? Just the last? Why?
  • The decisions on the previous point will affect the number of pipes opened in the parent vs the number opened by the children. You could always set up all the needed pipes in the parent, and let everyone do lots of closing. If you're only going to wait for the last process, you can optimize so that a given process in the chain has at most its input pipe and its output pipe open. Not trivial, but doable.
Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • *Yes.. i did parse the command line using cp and null.can i include the pipe and the file redirection in the same child process? –  Feb 15 '12 at 04:52