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
In reply to Re: Help to monitor a PID
by haukex
in thread Help to monitor a PID
by lsvolo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |