Ross Rogers
Ross Rogers

Reputation: 24270

In Perl, how can I do a non-blocking system call?

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.

Upvotes: 3

Views: 8000

Answers (2)

jrockway
jrockway

Reputation: 42704

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.

Upvotes: 4

Ian Clelland
Ian Clelland

Reputation: 44192

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.

Upvotes: 11

Related Questions