I'm trying to print the whole process table with php (Actually I'm trying to print all the php processes that are running on my server). This is the code I'm using:
var_dump(exec("ps -A | grep php"));
When I start the php file, it returns me its own PID but not the others that are already running. I've checked through ssh console and there are 7, and that code prints me just 1 and completelly different to the others PID's.
Any solution?
Thanks in advance.
I found the answer at PHP Manual: getmypid
function countProcesses($scriptName)
{
// ps aux|grep "[u]pdate.php"|wc -l
$first = substr($scriptName, 0, 1);
$rest = substr($scriptName, 1);
$name = '"['.$first.']'.$rest.'"';
$cmd = "ps aux | grep $name | wc -l";
$result = exec($cmd);
return $result;
}
This function returns the number of processes are already running so I just call echo countProcesses('php6'); and it brings me back the amount of processes running as php6.
Related
For monitoring purposes, I want to forward the amount of open files of the current process to our monitoring tool. In shell, the following command can be executed to get the desired information: ls /proc/PROCES_ID/fd | wc -l where PROCES_ID is the current process id. Is there a way to get this information natively in PHP?
To run any shell commands from within php script and get the output:
From PHP manual on exec() command
exec(string $command, array &$output = null, int &$result_code = null): string|false
For your command:
$output = []; // this array will hold whatever the output from the bash command
$result_code = null; // this will give you the result code returned, if needed
$command = '/proc/PROCES_ID/fd | wc -l'; // command to be run in the bash
exec($command, &$output, &$result_code);
//now you can look into $output array variable for the values returned from the above command
print_r($output);
But as mentioned in the comment, using bash script over php should be preferred if feasible.
I am trying to execute a mpi program using php as I have to provide a web-interface to user.PHP successfully executes the command and return output only If I have only one process, i.e
$output = system(" mpiexec -hostfile /data/hosts -np 1 /data/./hello",$returnValue);
But I have need more then one process and I have tried following ways but results are same i.e No response from the mpi program.
using system ()
$output = system(" mpiexec -hostfile /data/hosts -np 2 /data/./hello",$returnValue);
using shell_exec ()
$output = shell_exec(" mpiexec -hostfile /data/hosts -np 2 /data/./hello");
If I use these methodes to run a simple c program I do receive response.
$output = system("/data./hello",$returnValue);
Please assist me. Many thanks.
Problem seem to be that you are trying to store the output of "system()" into "$output" while it's already storing the value on "$returnValue". Try this:
exec('mpiexec -hostfile /data/hosts -np 2 /data/./hello', $var);
var_dump($var);
For some odd reason PHP doesn't get along with multi threads.
A dirty workarround will be to output the result to a file and feed php from that filem, something like:
system(" mpiexec -hostfile /data/hosts -np 2 /data/./hello > myfile.txt 2>&1");
$handle = file_get_contents('myfile.txt');
I need to start php process from shell on remove server with some arguments, so i thought that it should be a nice idea to make REST API, that executes some function when user performs GET request.
I wrote a simple bash script for testing and figured out that command-line argument is not being specified, when calling this script from website:
shell_exec('/var/www/test.sh 123')
Bash script source:
#!/bin/sh
echo $1;
When calling this bash script from root (or other existing user) it correctly shows argument it has received. When i call this script from website (that is running under user www-data under apache2), it returns nothing:
Also, if i execute this bash script in my console under www-data user, it also returns nothing:
su -c '/var/www/test.sh 123' www-data
Also i've tried to start process from different user from php (is supposed that this will not work for security reasons, but just in case):
$result = system("su -c '/var/www/test.sh 123' sexyuser", $data);
// var_dump($result): string(0) ""
// var_dump($data): int(1)
So, what privileges should i give to www-data user to run process under php?
You should let php run the script and handle the results
check php.net on exec for example http://www.php.net/manual/en/function.exec.php
//called by example.com/myshell.php?day=today&k=y&whatever=youwant
$arguments = implode(" ", $_GET);
$lastline_of_exec_result = exec ( "/your/command.sh ".$arguments); //sh called with today y youwant
echo $lastline_of_exec;
Where $arguments are the stringified list of ALL information your script got from GET arguments
if you want a ore precise in and output, try this:
//called by example.com/myshell.php?day=today&k=y&whatever=youwant
$argument = $_GET['whatever'];
$output = array();
$last_line = exec("your/command.sh ".$argument, &$output); //sh called with youwant
foreach($output as $line)
echo $line."<br/>".PHP_EOL;
or of course (with shell_exec)
$argument = $_GET['whatever'];
$output = shell_exec("your/command.sh ".$argument);
echo "<pre>".$output."</pre>";
make sure (shell_)exec is not listed under disable_functions in your php.ini
Background:
I'm trying to write a shell script using php that will automatically checkout a couple of large SVN repos. I am also using the PEAR console progress bar class to display the progress of the checkout (not totally necessary, but the thing that prompted my question).
Question:
Is there a way to run a loop that will update with every line output to STDIN on the commandline?
If I do
<?php shell_exec("svn co svn://my.repo.com/repo/trunk"); ?>
I get back all of the output from the command in a giant string.
Trying a loop like
<?php $bar = new Console_ProgressBar('%fraction% [%bar%] %percent% | %elapsed% :: %estimate%', '=>', ' ', 80, $total);
$bar->display(0);
stream_set_blocking(STDIN, 0);
$output = array();
$return = '';
exec("svn co $svnUrl $folder", $output, $return);
while (!isset($return))
{
$bar->update(count($output));
}
$bar->erase(); ?>
will display the bar but not update.
Any solutions?
========================= UPDATE =======================================
Here's the working code I came up with based on the answer (for future reference):
<?php
$bar = new Console_ProgressBar('%fraction% [%bar%] %percent% | %elapsed% :: %estimate%', '=>', ' ', 80, $total);
$handle = popen("/usr/bin/svn co $svnUrl $folder", 'r');
$elapsed = 0;
$bar->display($elapsed);
while ($line = fgets($handle))
{
$elapsed++;
$bar->update($elapsed);
}
pclose($handle);
?>
PHP is not multi-threaded. exec() and company will block your script until the exec'd task completes. There's no point in using the while() loop, because the loop will not even start running until the svn call has completed.
If you want to run multiple parallel svn's, you'll need to use popen() (or proc_open()), which gives you a filehandle from which you can read the external command's output, and have multiple such external commands at the same time.
Use Output Buffering
see:
http://php.net/manual/en/function.ob-start.php
http://php.net/manual/en/function.ob-flush.php
http://php.net/manual/en/function.ob-end-clean.php
and see some related:
PHP Output buffering on the command line
Kohana 3 Command line output buffering?
AS I understand your problem that php execute script synchronously. Thats mean cycle will be run only after exec command and output will not be changed because it already done. Try to use fork.
In php, how can I get the number of apache children that are currently available (status = SERVER_READY in the apache scoreboard)?
I'm really hoping there is a simple way to do this in php that I am missing.
You could execute a shell command of ps aux | grep httpd or ps aux | grep apache and count the number of lines in the output.
exec('ps aux | grep apache', $output);
$processes = count($output);
I'm not sure which status in the status column indicates that it's ready to accept a connection, but you can filter against that to get a count of ready processes.
If you have access to the Apache server status page, try using the ?auto flag:
http://yourserver/server-status?auto
The output is a machine-readable version of the status page. I believe you are looking for "IdleWorkers". Here's some simple PHP5 code to get you started. In real life you'd probably want to use cURL or a socket connection to initiate a timeout in case the server is offline.
<?php
$status = file('http://yourserver/server-status?auto');
foreach ($status as $line) {
if (substr($line, 0, 10) == 'IdleWorkers') {
$idle_workers = trim(substr($line, 12));
print $idle_workers;
break;
}
}
?>