Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re^2: Effect of redirecting output to /dev/null on $? value

by afoken (Canon)
on Aug 04, 2020 at 20:27 UTC ( #11120288=note: print w/replies, xml ) Need Help??

in reply to Re: Effect of redirecting output to /dev/null on $? value
in thread Effect of redirecting output to /dev/null on $? value

`exec my_executable_that_seg_faults > /dev/null`;

exec at the start of a command is one of the few things that are treated specially in Perl_do_exec3(), see Re^2: Improve pipe open? (redirect hook). It seems to disable the default optimization and forces the use of the default shell.

There is a way to stay mentally sane on Unix/POSIX systems for I/O-redirection. Don't use system; instead, fork and exec manually:

# (untested) my $pid=fork(); my @cmd_and_args=('my_executable_that_seg_faults'); # maybe push @cmd_and_args,qw( some arguments for the program ); defined($pid) or die "Can't fork: $!"; if ($pid) { # parent process waitpid $pid; #<-- sets $? } else { # child process open STDOUT,'>','/dev/null' or die "Can't redirect STDOUT: $!"; exec { $cmd_and_args[0] } @cmd_and_args; die "exec failed: $!"; }

Note that ONLY indirect object notation on exec prevents all attempts of perl to be smart. See The problem of "the" default shell.


Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

Replies are listed 'Best First'.
Re^3: Effect of redirecting output to /dev/null on $? value
by jcb (Parson) on Aug 05, 2020 at 00:01 UTC

    I have used this before, but our questioner seemed to be asking for a minimal solution. This strategy is the only way if you need more than the basic pipes, but (having just checked) IPC::Open3 is actually implemented using system, presumably for compatibility on Windows, where fork must be emulated.

      open3 only uses system in Windows and OS/2; fork is used elsewhere.

Re^3: Effect of redirecting output to /dev/null on $? value
by ikegami (Pope) on Aug 05, 2020 at 04:03 UTC

    That's horrible advice.

    The OP is complaining about errors being misreported, and you introduce a new such error.

    exec failures should not appears as exit code from a successfully launched child. Even system and open3 get that right. (They use a close-on-exec pipe to communicate the errno of failures to the parent.)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11120288]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (9)
As of 2021-03-02 21:36 GMT
Find Nodes?
    Voting Booth?
    My favorite kind of desktop background is:

    Results (63 votes). Check out past polls.