Hide terminal output from Execve

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 */

  ...