0

Possible Duplicate:
How can I run Perl system commands in the background?

I have a simple Perl program that triggers another process, dependent on the outcome of an if statement. However, I cannot continue sending commands until the triggered process is complete. I presume this is because the 'system' function waits for a return value of the process before continuing.

while (bla bla bla) {
  if (command is bla) { 
    system("osascript 'something.app'");
  } else { 
    print $client "invalid command\r\n";
  } 
} continue {
  …etc

In short, my script won't continue until it hears something back from something.app. Any way round this?

Community
  • 1
  • 1
rom
  • 540
  • 2
  • 5
  • 9
  • It's a [FAQ](http://learn.perl.org/faq/perlfaq8.html#How-do-I-start-a-process-in-the-background-). Previously on SO: http://stackoverflow.com/questions/2133910/how-can-i-fire-and-forget-a-process-in-perl http://stackoverflow.com/questions/2711520/how-can-i-run-perl-system-commands-in-the-background http://stackoverflow.com/questions/4053093/how-can-i-make-fork-in-perl-in-different-scripts – daxim Dec 03 '11 at 14:25

2 Answers2

4

An exec within a fork will work without blocking execution:

if (command is bla) { 
    exec "osascript 'something.app'" if fork;
} else { 
    print $client "invalid command\r\n";
}
Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
  • You'll need something to reap the child processes when they exit with this method. A SIGCHLD handler would work perfectly. – Rob K Dec 03 '11 at 16:00
  • I hope, main script will end execution shortly. otherwise when executed oascript will end, it will change its status to 'zombie', and will send SIGCHLD signal to your script. You can make very simple handler for this situation. But when main script will end first, then child command will be move into foster parent, it is init process. this process will handle 'wait' command automatically for ended process. Some code for this you can find here: http://perldoc.perl.org/perlipc.html – Znik Sep 16 '16 at 11:36
1

On Unix/Linux you can 'amp it off'

system( "osascript 'something.app' & " );

Adding the '&' tells the shell to run the process in the background. I don't remember if the "grandchild" process gets re-parented or not, so you may need a SIGCHLD handler to reap the child processes when they exit.

I think there's a way to do the same thing on windows, but I can't remember it at the moment. Maybe "start /b ".

http://perldoc.perl.org/functions/system.html http://perldoc.perl.org/perlipc.html#Signals

Rob K
  • 8,757
  • 2
  • 32
  • 36