I want to write a php script for monitoring particular process using top command and write into the file.

I use top -p pid for monitoring a particular process and also i write a shell script for that.

#!/bin/bash

FILE="/home/test/nik/myscriptoutput2";
TIMEOUT=5;
PROCNAME='init';
counter=0;

echo 'counter value is :- '$counter
while [ $counter -lt 3 ]
do
        echo 'inside while'
        top -b -n 1 |grep $PROCNAME >> $FILE
        sleep $TIMEOUT
        counter=$((counter+1))
        echo $counter
done
echo 'while loop end'

This script will monitor init process after 5 sec for 3 times and write the it into file.

How can I write the same script in PHP?

Why not use

top -bd 5 -n 3 -p `pidof init` >> /home/test/nik/myscriptoutput2

instead of your whole script...

In PHP you can use

<?php
   $file  = "/home/test/nik/myscriptoutput2";
   $output = shell_exec('top -bd 5 -n 3 -p `pidof init`');
   file_put_contents($file, $output);
?>
  • Thank you it working successfully but using top -b -n 1 |grep init command. – Nikhil Patil May 22 '15 at 11:50
  • top -bd 5 -n 3 -p pidof init this command is not working it will show error (top: bad pid 'pidof init') – Nikhil Patil May 22 '15 at 11:51
  • You need to use backticks (`) instead of single quotes ('). – Lambert May 22 '15 at 11:53

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.