bobhussey has asked for the wisdom of the Perl Monks concerning the following question:

I want to start a process in the background, redirect it's output to a file, and get the pid of the process i just started. Is there a way to do all of this (I can figure out how to do any two of the 3 but not all three). Thanks, Bob
  • Comment on Doing a system command and getting the pid

Replies are listed 'Best First'.
Re: Doing a system command and getting the pid
by borisz (Canon) on Jan 21, 2005 at 00:35 UTC
    untested:
    my $pid = open( my $fh, 'your_command 1>/tmp/xxx 2>&1 |' );
    Boris
Re: Doing a system command and getting the pid
by Tanktalus (Canon) on Jan 21, 2005 at 00:25 UTC

    It'd be nice if you gave us what you had tried. It really does help. Anyway ... Off the top of my head, untested:

    FORK: { if (my $child = fork()) { print "Child process ID: $child\n"; } elsif (not defined $child) { # failed to fork. next FORK; } else { # child. open(STDOUT, '>somefile); close(STDIN); # just good practice for background procs exec($program, @program_args); } }
    Update: Fixed the off-by-everything error as noted by Eimi Metamorphoumai - thanks!

      I think you've got your if backwards. fork returns zero to the child, and gives the parent the child's pid, so you want to do your exec in the case that $child is 0 (but defined).
Re: Doing a system command and getting the pid
by eyepopslikeamosquito (Archbishop) on Jan 21, 2005 at 04:44 UTC