Reputation: 61
I am developing a CLI PHP script that can either be executed in the foreground or the background. If running in the foreground I want to be able to interact with the user getting input information. Obviously if the script is launched in the background using the '&' parameter any user interaction should be skipped...
So is there a way for a PHP script to detect that it has been launched in the background?
Upvotes: 1
Views: 376
Reputation: 2018
This is how I do it:
if (!stream_isatty(STDIN)) {
echo "Running in background\n";
}
As mentioned above, this is basically the same as how it is usually done in C/C++. I can recall doing this when I was writing C programs for Unix 30+ years ago.
Upvotes: 0
Reputation: 12581
There's a Unix frequently asked question (which I found via this Stack Overflow post) that basically claims it cannot reliably be done. One suggestion the article gives is to check whether or not stdin
is a terminal:
sh: if [ -t 0 ]; then ... fi
C: if(isatty(0)) { ... }
I agree with Pekka's comment that you should simply provide a parameter to the script. The -i
(for interactive) option is sometimes used for this express purpose. If that parameter isn't passed, you can assume you're in "automated" mode.
Upvotes: 1
Reputation: 57650
Its not possible to detect if its running in background. I still didn't find any way to do.
One way could be to traverse process list and check the status of /usr/bin/php
The best ways is to use a parameter (say --daemon
). When this parameter is passed it'll be running in background otherwise it'll print useful information on front-end.
You can create daemon using System_Daemon pear package.
Upvotes: 1