1

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?

TimWolla
  • 31,849
  • 8
  • 63
  • 96
Rich06
  • 61
  • 4
  • 1
    I don't know - there may be on system level. But wouldn't it be much, much simpler to just pass a parameter to the script? – Pekka Jan 22 '12 at 15:37
  • possible duplicate of [How can a C/C++ process know if it runs in background?](http://stackoverflow.com/questions/3940555/how-can-a-c-c-process-know-if-it-runs-in-background) – mario Jan 22 '12 at 15:48

2 Answers2

1

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.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
1

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.

Community
  • 1
  • 1
Jonah Bishop
  • 12,279
  • 6
  • 49
  • 74