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?
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.
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.
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.
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 */
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With