Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Get the LINUX PID of a command

Tags:

linux

php

ubuntu

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!

like image 623
Skylineman Avatar asked Mar 02 '26 10:03

Skylineman


2 Answers

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.
like image 165
romaninsh Avatar answered Mar 04 '26 23:03

romaninsh


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

like image 27
0xd Avatar answered Mar 05 '26 00:03

0xd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!