9

How can I spawn a process in a PHP page in order to start a program that survives the execution time of the request?

In other words, I want the page to have a normal lifetime (few milliseconds) but launch a program that keeps running on the server. Thanks

pistacchio
  • 53,670
  • 101
  • 270
  • 404
  • 1
    Here's [a helpful tutorial on this topic](http://tuxradar.com/practicalphp/16/1/0) that I've referenced many times. You may have to get a few pages in to get specifically to process forking, but the whole bit is worth absorbing if you want to get into process management with php. – rdlowrey Jan 21 '12 at 21:15
  • @rdlowrey that link is no longer valid – rineez May 31 '18 at 04:59

2 Answers2

16

Use this code:

<?php exec('nohup /usr/bin/my-command > /dev/null 2>&1 &'); ?>

This forks the sub-process into the background and writes all of the output into /dev/null. That way PHP continues executing the script as if there won't be any output it has to wait for.

mojuba
  • 11,258
  • 6
  • 49
  • 68
TimWolla
  • 30,523
  • 8
  • 64
  • 89
-1

I would suggest you to use CRON if you need to start a process on a time basis.

JanLikar
  • 1,216
  • 8
  • 20
  • I don't the the original poster wants to know how to start a program at a certain time, which is what CRON does. Rather, the question is about having a web page written in PHP start a background process whenever someone goes to that page. That doesn't necessarily happen at a certain time. – Clint Brown May 29 '21 at 06:16