[TUHS] Shell builtin exec

Warren Toomey wkt at tuhs.org
Wed Aug 21 08:00:33 AEST 2019

On Tue, Aug 20, 2019 at 02:10:55PM -0700, Adam Thornton wrote:
>    This is probably the place to ask:
>    I understand why the shell builtin "exec" is the same as the syscall
>    exec() in the sense of "replace this process with that one."  But why
>    is it also the way to redirect filehandles in the current shell?  (That
>    is, why isn't the redirection named something else?)

exec() doesn't do anything with file handles; it simply replaces the
executable code in the current process. Here's the pseudo-code for a
shell where redirection is done.

  int pid;                      /* Holds the process-id of the child */

  switch (pid = fork())         /* Call fork, and test what it returns */
    case -1: printf("The fork failed\n"); return (-1);

    case 0:              /* The child is given a value of 0 from fork() */
                           /* Do special things like closing files etc. */

    if (redirection required) {
      close my standard output;
      open the named output file as my standard output;

                                /* Replace ourselves with the real child */
                                /* Call execvp */
      execlp(command, arg1, arg2, ..., NULL);
      exit(1);                  /* Exec failed, indicate error */

    default:          /* The parent receives the new process-id from fork() */
      wait();                   /* Wait for child to exit */

So the child shell itself does the redirection after the fork(), but before
it replaces itself with the new executable code.

Cheers, Warren

More information about the TUHS mailing list