I don’t know about PHP specifically, but you can go to the process tree until you find either init or cron.
Assuming PHP can get its own process id and run external commands, ps -ef | grep pid ps -ef | grep pid , where pid is your own process identifier and extract the parent process identifier (PPID) from it.
Then do the same with this PPID until you reach cron as the parent or init as the parent.
For example, this is my process tree, and you can see the ownership chain, 1 → 6386 → 6390 → 6408.
UID PID PPID C STIME TTY TIME CMD root 1 0 0 16:21 ? 00:00:00 /sbin/init allan 6386 1 0 19:04 ? 00:00:00 gnome-terminal --geom... allan 6390 6386 0 19:04 pts/0 00:00:00 bash allan 6408 6390 0 19:04 pts/0 00:00:00 ps -ef
The same processes that run in cron will look like this:
UID PID PPID C STIME TTY TIME CMD root 1 0 0 16:21 ? 00:00:00 /sbin/init root 5704 1 0 16:22 ? 00:00:00 /usr/sbin/cron allan 6390 5704 0 19:04 pts/0 00:00:00 bash allan 6408 6390 0 19:04 pts/0 00:00:00 ps -ef
This “fit the process tree” solution means that you don’t have to worry about entering an artificial parameter to indicate whether it is running under cron or not - you can forget to do this in your interactive session and in other things up.
paxdiablo Oct 10 '08 at 11:10 2008-10-10 11:10
source share