Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP spawn process

Tags:

php

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

like image 834
pistacchio Avatar asked Jan 21 '12 21:01

pistacchio


People also ask

How to run background process in PHP?

So, to run any background process from PHP, we can simply use either exec or shell_exec function to execute any terminal command and in that command, we can simply add & at the last so that, the process can run in the background.

How do I know if PHP script is running?

If you have long running batch processes with PHP that are run by cron and you want to ensure there's only ever one running copy of the script, you can use the functions getmypid() and posix_kill() to check to see if you already have a copy of the process running.


1 Answers

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.

like image 64
TimWolla Avatar answered Sep 28 '22 00:09

TimWolla