redirect a process started with execv to /dev/null

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

Share

Follow

edited Nov 21, 2012 at 11:03

CAMOBAP

5,41788 gold badges5757 silver badges9292 bronze badges

asked Nov 21, 2012 at 10:54

Alon_T

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"?

    – Olaf Dietsche

    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. The dup2 sets standard out to /dev/null, and this will not be changed by the execv.

    – James Kanze

    Nov 21, 2012 at 11:14

Add a comment

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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值