Search code examples
cprocesshideoutputfork

Hide terminal output from Execve


I'm making a C program where it basically reads in a line from the user, interprets it and then tries to execute the command with execve. I'm also forking the execve to a child process if '&' is in the input.

Now I wish to hide any terminal output which comes from the execve command when it's running in the child process. Is there any relatively easy way to do this?


Solution

  • You can hide the output by redirecting stdout and stderr to /dev/null after forking but before execve(). The idea is to open /dev/null, then make stdout and stderr duplicates of the obtained file descriptor with dup2() (which will also close the originals first). It's almost the same as redirecting to a pipe.

    An example (incomplete program, and skipping most error checking):

      #include <unistd.h>
      #include <fcntl.h>
      ...
    
      int pid = fork();
      if (pid == -1) {
        /* fork error */
        exit(1);
      } else if (pid == 0) {
        /* child process */
    
        /* open /dev/null for writing */
        int fd = open("/dev/null", O_WRONLY);
    
        dup2(fd, 1);    /* make stdout a copy of fd (> /dev/null) */
        dup2(fd, 2);    /* ...and same with stderr */
        close(fd);      /* close fd */
    
        /* stdout and stderr now write to /dev/null */
        /* ready to call exec */
    
        execve(cmd, args, env);
        exit(1);
      } else {
        /* parent process */
    
      ...