tags:

views:

220

answers:

2

In Perl, without using the Thread library, what is the simplest way to spawn off a system call so that it is non-blocking? Can you do this while avoiding fork() as well?

EDIT Clarification. I want to avoid an explicit and messy call to fork.

+7  A: 

Do you mean like this?

system('my_command_which_will_not_block &');

As Chris Kloberdanz points out, this will call fork() implicitly -- there's really no other way for perl to do it; especially if you want the perl interpreter to continue running while the command executes.

The & character in the command is a shell meta-character -- perl sees this and passes the argument to system() to the shell (usually bash) for execution, rather than running it directly with an execv() call. & tells bash to fork again, run the command in the background, and exit immediately, returning control to perl while the command continues to execute.

Ian Clelland
Doesn't system implicitly use fork() though?
Chris Kloberdanz
Clarification. I want to avoid an explicit and messy call to fork.
Ross Rogers
**Sigh** I *guess* a "non-blocking system call" *could* mean that.
Sinan Ünür
Sinan: Yeah, I took "system call" to mean "perl system() call", rather than an OS kernel system call -- lucky guess on my part, I suppose :)
Ian Clelland
sry for the confusion. Thanks all.
Ross Rogers
+1  A: 

The post above says "there's no other way for perl to do it", which is not true.

Since you mentioned file deletion, take a look at IO::AIO. This performs the system calls in another thread (POSIX thread, not Perl pseudothread); you schedule the request with aio_rmtree and when that's done, the module will call a function in your program. In the mean time, your program can do anything else it wants to.

Doing things in another POSIX thread is actually a generally useful technique. (A special hacked version of) Coro uses it to preempt coroutines (time slicing), and EV::Loop::Async uses it to deliver event notifications even when Perl is doing something other than waiting for events.

jrockway