in reply to Capturing stdout and segfault of a program

Do you have to do it from within the program itself, or can you use a wrapper program? You generally can't recover from a SIGSEGV, but a wrapper program can easily see that a child process died from a signal and which one (from $?, and can also easily capture its output by setting up pipes as the child process's STDIN and STDOUT.

Replies are listed 'Best First'.
Re^2: Capturing stdout and segfault of a program
by Gmong (Novice) on Mar 07, 2005 at 20:53 UTC
    The perl script itself is the wrapper to the program. I have gotten to this stage now

    #!/usr/bin/perl -w use POSIX qw(:signal_h :errno_h :sys_wait_h); $command = $ARGV[0]; parse(); if (!defined ($pid = fork())) { die "cannot fork: $!"; } elsif ($pid == 0) { exec("$command"); } else { waitpid($pid, 0); if (WIFEXITED($?)) { print "Exited\n"; } elsif (WIFSIGNALED($?)) { $sig = WTERMSIG($?); if ($sig == 11) { print "Segfault\n"; exit 11; } print "Signaled $sig\n"; } else { print "EH\n"; } } close STDOUT; exit 0; sub parse { my $pid; return if $pid = open(STDOUT, "|- "); die "cannot fork: $!" unless defined $pid; while (my $line = <STDIN>) { print "$line"; } exit; }
    So I am able to capture the program and take note of when it segfaults, and also parse the programs standard out. All I am missing now is capturing the programs stderr...

    Apart from using IO::Capture is there another way that will simply add to the above code, or is this just wishful thinking?

    Thank you very much to everyone who have replied to my question.

      First, see if IPC::Open3 can do what you want. You would use it instead of fork and exec.

      If it doesn't, you'll want to create filehandles for your child process with pipe, then assign them to STDIN, STDOUT, and STDERR after the fork, using POSIX::dup2 or similar.

        Thank you for the reply :)