Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 698
log234 Avatar asked Oct 19 '14 17:10

log234


People also ask

How do I hide terminal output in Linux?

To silence the output of a command, we redirect either stdout or stderr — or both — to /dev/null. To select which stream to redirect, we need to provide the FD number to the redirection operator.

How do I stop terminal output?

If you want to force quit “kill” a running command, you can use “Ctrl + C”. most of the applications running from the terminal will be forced to quit.

What is Execv command in Linux?

execv(path,argv) causes the current process to abandon the program that it is running and start running the program in file path. Parameter argv is the argument vector for the command, with a null pointer at the end. It is an array of strings.


1 Answers

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

  ...
like image 139
Dmitri Avatar answered Oct 06 '22 10:10

Dmitri