Dan Hastings
Dan Hastings

Reputation: 3290

Get program name for PID using PHP

I am attempting to do something that is a little risky. Its a private script, but i want to add some security so I don't accidentally enter an invalid PID.

Currently if a script hangs it will lock up the port it uses, i need to kill the PID and then restart it. I want to add a new argument to this script so i can pass in the old PID and the script will kill that PID before starting again. Using netstat -tulpen i see that there is a program name tied to a PID. I want to make sure that the program name is PHP so i dont shut down a different process by accident. E.g. check that PID 15498 was created by PHP (15498/php)

tcp        0      0 0.0.0.0:1067            0.0.0.0:*               LISTEN      0          201425     15498/php

I had a look on the file system and i found a directory for the PID, but all of the files within this directory are empty. /proc/15498

Once i can validate that this is a relatively safe PID to kill i can then run the command to kill it.

exec("kill -SIGKILL 15498");

Upvotes: 1

Views: 1687

Answers (3)

Janos Szabo
Janos Szabo

Reputation: 1352

To be able to check for process with arguments use this:

$cmd = str_replace("\0", " ", trim(file_get_contents("/proc/$pid/cmdline"), "\0"));

Upvotes: 0

Barmar
Barmar

Reputation: 782785

Get the command line from /proc/PID/cmdline, and remove the trailing null byte.

$cmd = trim(file_get_contents("/proc/$pid/cmdline"), "\0");

Upvotes: 4

user282623
user282623

Reputation: 1

You could use the system php call and pass it the shell command to look up process information which then you can pipe through grep with the PID to look up the process name

Upvotes: -1

Related Questions