I'm writing a PHP script to start and monitor processes. I used to use ps <pid> to do this but in rare cases it's not reliable as there was an irrelevant process running by the same pid after my process actually ended.

So I wanted to add a random string in my command so my PHP script can be sure it's the process it started. What are my options to do this?

Thus far I came up with this:

"USELESS_VAR_0nQjdXR45P=\"{$cmdRandomString}\" | $cmd"

Wherein $cmd is the actual command that I wanted to run. $cmdRandomString is the random string I added in. But for some reason, in ps aux isn't displaying the useless var here.

Is it because it quickly finished?

I also tried to add a dummy command option like --xxxx=yyyy but the command would return a fatal error not knowing the option.

Is there any way to do this? Or is there any reliable way to identify a process other than the unreliable pid?

  • Try FOO=bar cmd ... (no |, no quotes) and ps axue. – dirkt Jul 7 '17 at 11:58
  • @dirkt It doesn't work. $cmd is a series of commands { xxx; xxx; } – datasn.io Jul 7 '17 at 12:18
  • 1
    It would help to precisely describe what you actually want instead of introducing simplifications. A series of commands will execute in series (duh), so do FOO=bar1 xxx1; FOO=bar2 xxx2 for each of the commands you want to identify. You won't be able to see the sequence as a whole. – dirkt Jul 7 '17 at 12:23
  • 1
    Would it be a help to additionally grep for the command name? Or to use ps -C $cmd? Using pgrep instead? – Jaleks Jul 7 '17 at 12:45

Is there any reliable way to identify a process other than the unreliable pid?

The way to do this reliably is by starting the process yourself, and catching when it dies, e.g. you receive the unix signal SIGCHILD. The pid will continue to exist (in a state which is called "zombie") until you consume the child death notification e.g. waitpid().

In some cases you would need to delegate this to a process supervisor daemon, for example systemd. E.g. then you could query it using systemctl status my-process.service. This would be useful if you had a PHP web page, that needed to start a long-running process like a daemon.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.