Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: How do you launch a background process and get pid?

by graff (Chancellor)
on Apr 18, 2016 at 09:24 UTC ( [id://1160779]=note: print w/replies, xml ) Need Help??


in reply to How do you launch a background process and get pid?

Just to clarify what AM said above: because you are using both redirection and backgrounding in the string passed to "exec", a shell process has to be launched to execute that command line, and the shell exits. If you don't background it, the shell will keep running for as long as the sleep, and your "ps ax | grep sleep" step will show three lines of output - the additional line would be the shell process that is running "sleep 30".

Apart from that, you should be aware that the "exit" statement in your "if" block is never reached -- as stated in the perlfunc manpage, the "exec" call never returns.

If you remove both backgrounding and redirection from the command line string, your parent perl process will get the pid for the child sleep process, because "exec" won't have to invoke a shell to run the command -- i.e. you could do either this:

exec( "sleep 30" );
or this:
exec( "sleep", "30" );

Replies are listed 'Best First'.
Re^2: How do you launch a background process and get pid?
by bt101 (Acolyte) on Apr 18, 2016 at 16:33 UTC
    Thanks. I found this thread for suppressing the output:http://www.perlmonks.org/?node_id=53870 The code now looks like this:
    #!/usr/bin/perl use strict; use warnings; my $pid = fork; if ((defined $pid) && ($pid == 0)) { open(STDOUT, "/dev/null"); # suppressing output open(STDERR, "/dev/null"); # suppressing output exec("sleep", "30"); exit; } print "child pid [$pid]\n";
      open(STDOUT, "/dev/null"); # suppressing output open(STDERR, "/dev/null"); # suppressing output

      Yes, this suppresses output, but accidentally. You open STDOUT and STDERR for input. That may confuse your child process. What you really want is the three-argument form of open, used for output:

      open STDOUT,'>','/dev/null'; open STDERR,'>','/dev/null';

      Alexander

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-04-19 21:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found