How can I run a system command in Perl asynchronously?

There’s a LOT of ways to do this:

  • You can do this with a fork (perldoc -f fork)
  • or using threads (perldoc threads). Both of these make passing the returned information back to the main program difficult.
  • On systems that support it, you can set an alarm (perldoc -f alarm) and then clean up in the signal handler.
  • You can use an event loop like POE or Coro.
  • Instead of the backticks, you can use open() or respectively open2 or open3 (cf. IPC::Open2, IPC::Open3) to start a program while getting its STDOUT/STDERR via a file handle. Run non-blocking read operations on it. (perldoc -f select and probably google “perl nonblocking read”)
  • As a more powerful variant of the openX()’s, check out IPC::Run/IPC::Cmd.
  • Probably tons I can’t think of in the middle of the night.

Leave a Comment