13

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
  • 56,889
  • 107
  • 278
  • 420
  • 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. –  Jan 21 '12 at 21:15
  • @rdlowrey that link is no longer valid – rineez May 31 '18 at 04:59
  • 1
    @rineez try [Wayback Machine](https://web.archive.org/web/20140627231234/https://tuxradar.com/practicalphp/16/1/0) – JSON Nov 10 '22 at 02:33

2 Answers2

21

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,842
  • 9
  • 51
  • 72
TimWolla
  • 31,849
  • 8
  • 63
  • 96
-1

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

JanLikar
  • 1,296
  • 9
  • 22
  • 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