Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Help to monitor a PID

by haukex (Archbishop)
on Sep 13, 2016 at 10:14 UTC ( [id://1171654]=note: print w/replies, xml ) Need Help??


in reply to Help to monitor a PID

Hi lsvolo,

As Cuhulain has already pointed out, the string $pid will have a newline at the end, which you can remove with chomp, e.g. chomp($pid); This won't help if pgrep happens to return multiple PIDs - in this case I would recommend assigning the return value of the backticks to an array - see the description of backticks in list context in Quote-Like Operators in perlop. I've given an example using join below.

As for your second question, look at the order in which your loop is doing things: print the message, then get the status of the process, then sleep for 10 seconds, then repeat (print the message, etc.). That's why you're getting the old status. If you move the pgrep call to just before the print, then you'll get the most recent status.

As a general suggestion, I'd strongly recommend you use strict, see for example Use strict and warnings. Although your code looks ok for now, strict will help avoid programming mistakes.

Here's how I might write the same script; have a look and if you have any questions about understanding then feel free to ask. I'm using IPC::System::Simple's capturex function to replace the backticks (`...`).

#!/usr/bin/env perl use warnings; use strict; use IPC::System::Simple 'capturex'; my @cmd = ('pgrep','-f','bash'); my $msg = "Alive"; my $outfile = 'file.txt'; my $count = 5; my $sleeptime = 1; open my $fh, '>>', $outfile or die "Could not open $outfile! $!"; for (1..$count) { my $timestamp = localtime(time); my @pids = capturex(@cmd); chomp(@pids); if (@pids) { print $fh join(',',@pids) . " , $timestamp , $msg\n"; } else { print $fh "No pid , $timestamp\n"; } sleep $sleeptime; } print $fh "Time over , ".localtime(time)."\n"; close $fh;

Hope this helps,
-- Hauke D

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1171654]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (6)
As of 2024-04-20 02:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found