Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing all running processes on server using PHP

I am trying to get a list of all processes currently running on my Ubuntu server using PHP. Ideally, I would like to get the following information:

  • The Process ID
  • The Command Used to Execute the Process
  • The Arguments Given to the Process

I know that I can use exec to call ps to list the currently running processes.

exec('ps aux', $output);

However, the output is formatted with arbitrary number of spaces, so parsing it is not the easiest thing in the world.

I could potentially use explode or preg_split to parse, but is there an easier way to get a list of all running processes using php, along with the process id, command, and arguments?

like image 726
Zsw Avatar asked Sep 12 '15 06:09

Zsw


2 Answers

Most of the credit goes to meuh.


ps ahxwwo pid,command

Gives me the three items I need, but it is still rather difficult to parse due to arbitrary space formatting.

However, it is possible to remove the space formatting.

ps ahxwwo pid:1,command:1

Using explode with a white space as the delimiter now guarantees that index 0 is the pid, and index 1 is the command, and the remaining indices are arguments.

like image 167
Zsw Avatar answered Oct 19 '22 00:10

Zsw


I don't see anything simpler than ps with the right args, eg:ahxwwo pid,command which gives just the info you want, eg:

5911 tail -F /var/log/mail.log

If you want raw data you can read each file in /proc/[123456789]*/cmdline. For example,

$ cat -vet /proc/5911/cmdline
tail^@-F^@/var/log/mail.log^@

where the command arguments are separated by a null character.

like image 44
meuh Avatar answered Oct 19 '22 00:10

meuh