3

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
  • 2
    Fork is the idiom of the OS for processes--there is no reason to avoid forking on nix systems. But there are always reasons to encapsulate and homogenize access points.
    – Axeman
    Oct 20, 2009 at 19:00
  • 3
    What is messy about fork, and why do you want to avoid an explicit one?
    – Ether
    Oct 20, 2009 at 19:19
  • 3
    Just learn how to fork. Then you'll know. I'm not sure why you think it is messy. Oct 20, 2009 at 20:39
  • 1
    @RossRogers I know it's an old question, but maybe next seekers will find this helpfull, just use system("START " . $cmd);
    – John Doe
    Feb 17, 2017 at 15:16
  • 1
    There is no START on Linux. Feb 17, 2017 at 20:51

2 Answers 2

11

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.

6
  • Doesn't system implicitly use fork() though? Oct 20, 2009 at 17:50
  • Clarification. I want to avoid an explicit and messy call to fork. Oct 20, 2009 at 17:55
  • 1
    Sigh I guess a "non-blocking system call" could mean that. Oct 20, 2009 at 18:02
  • 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 :) Oct 20, 2009 at 18:49
  • sry for the confusion. Thanks all. Oct 20, 2009 at 19:47
4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.