Skylineman
Skylineman

Reputation: 576

PHP: Get the LINUX PID of a command

I'm running a command in my linux server (Ubuntu). For example:

screen -A -h 1500 -m -dmS test_command_one /home/SKY-users/SKY-001/./script

Is there any way to the PID of this background progress which screen name is: test_command_one?

ps aux | grep test_command_one:

root      6573  8.1  2.4 271688 123804 pts/4   Ss+  Oct19   3:04 /home/SKY-users/SKY-001/./ ...

I'd like to get back this PID: 6573

PHP: (easy)

<?php 
$output = shell_exec('sudo ps aux | grep test_command_one');
$array = explode("\n", $output);
echo '<pre>'.print_r($array, true).'</pre>';
?>

Thanks for help!

Upvotes: 2

Views: 14800

Answers (5)

Christian Melius
Christian Melius

Reputation: 1

Or, just use:

$pid = getmypid();

Upvotes: -2

Juan Girini
Juan Girini

Reputation: 1168

$pid = shell_exec($cmd . " && echo $!");

Upvotes: -1

sneils
sneils

Reputation: 62

You could also try this:

echo exec('pidof test_command_one');

It's shorter ;)

See also: pidof manpage

Upvotes: 1

romaninsh
romaninsh

Reputation: 10664

Edit:

By combining with code by @WagnerVaz

$mystring = "test_command_one";
exec("ps aux | grep 'screen .* $mystring' | grep -v grep | awk '{ print $2 }' | head -1", $out);
print "The PID is: " . $out[0];

Explanation

  • ps aux - shows processes for all users and hidden processes too
  • grep - filters only lines containing "screen" and then "test_command_one" in the same line
  • grep -v - removes from output the very same line which we are executing, because it will also be matched
  • awk '{ print $2 }' - awk splits input into columns and uses multiple spaces as separator. This print contents of 2nd column
  • head -1 - limits output only to the first line. This is in case you have multiple screen running, only first ID is returned.

Upvotes: 17

0xd
0xd

Reputation: 1901

Try this:

<?php
    $mystring = "test_command_one";
    exec("ps aux | grep \"${mystring}\" | grep -v grep | awk '{ print $2 }' | head -1", $out);
    print "The PID is: " . $out[0];
?>

Edited: Combined with shell exec of @romaninsh

Upvotes: 2

Related Questions