redirect a process started with execv to /dev/null
1
I have a program that forks()
, and the child process is replaced by another process, say A, that is ran through invoking execv(A)
.
How do I redirect process A
's output to /dev/null
??
I've so far tried : (The handle error parts are taken care of, and no error occurs)
pid = fork();
//check for errors
if (pid<0){
//handle error
}
//the child process runs here
if (pid==0){
fd = open("/dev/null", O_WRONLY);
if(fd < 0){
//hadnle error
}
if ( dup2( fd, 1 ) != 1 ) {
//handle error
}
if (execv(lgulppath.c_str(),args)<0){
//handle error
}
}
However, that, understandably doesn't work , since it redirects the child process's output to /dev/null
and not process A
's, later to replace the child, output.
Any ideas? (I don't have the code of A
's process)
Thanks
Follow
5,41788 gold badges5757 silver badges9292 bronze badges
asked Nov 21, 2012 at 10:54
1,42044 gold badges2525 silver badges4545 bronze badges
- Your code looks correct. Where do you get an error? Why do you say "this understandably doesn't work"? Nov 21, 2012 at 11:04
- @OlafDietsche, notice that the open and dup2 are invoked before execv is, when open and dup2 are invoked, they redirect the child's process's output to /dev/null.However, when execv is invoked it replaces the child process, and process A's(the one that replaced the child process) will now outputs to stdout and not /dev/null
– Alon_T
Nov 21, 2012 at 11:09 - @user1432779
execv
replaces the executable image. It does not change any open files. Thedup2
sets standard out to/dev/null
, and this will not be changed by theexecv
. Nov 21, 2012 at 11:14
1 Answer
Sorted by:
1
One possibility could be, that process A writes to stderr
instead of stdout
.
Then you must dup2(fd, 2)
instead.
If process A writes to stdout
and stderr
, you must dup2()
both:
if (dup2(fd, 1) < 0) {
// error handling
}
if (dup2(fd, 2) < 0) {
// error handling
}