2

I'm trying to output a system netstat -an -p TCP $interval > $log for a sleep of $seconds, and then quit/kill the netstat command but am having trouble getting it to work correctly.

If I use start netstat..., my sleep and kill commands work, but it does not write to the log.

If I only use netstat..., then it writes to the logs, but will not move on to the sleep and kill commands.

Any ideas on how to solve this??

$netstat_cmd = "netstat -an -p TCP $interval >$netstatlog;
$stop_netstat_cmd = "c:\utilities\pskill NETSTAT.exe";
system($netstat_cmd);
sleep $seconds;
system "$stop_netstat_cmd";

Thanks!

Alex
  • 5,863
  • 2
  • 29
  • 46
user967536
  • 37
  • 5
  • 2
    It'd be easier to make suggestions if we could see the source code. Also, `start` smells a lot like Windows, which might influence the answers. If this is on Windows system, please add [tag:windows] to the tags on the question. Thanks! – sarnold Oct 19 '11 at 00:45
  • Yes, this is for windows..will add code a little later, this typing not working so well from mobile device. – user967536 Oct 19 '11 at 00:54
  • Don't try to get your source into the comments; it just won't work well. Instead, use the [edit] link under your question to add the source there. Thanks! – sarnold Oct 19 '11 at 00:56

3 Answers3

2

Why don't you use IPC::Run? It has a kill_kill() method that is portable across Unix and Win32 (the latter is important if you're running on Windows as your "start" seems to possibly indicate).


As far as your own approach, the start xxx redirect doesn't work, so the easiest fix is to:

  • Create a batch file to run netstat and redirect to a file

  • Launch the batch file with start

DVK
  • 126,886
  • 32
  • 213
  • 327
0

Your trouble is that system() runs its command and waits for it to return, so you never get as far as calling sleep(). You need to run netstat from another process, or in the background. You can use fork() to acheive this, by spawning another process from your main process, and having that run netstat:

my $interval = 5;
my $netstatlog = "foo.tmp";
my $seconds = 10;

my $netstat_cmd = "netstat -an -p TCP $interval >$netstatlog";
my $stop_netstat_cmd = "pskill NETSTAT.exe";

if (my $pid = fork()) { # make new process
    print "launched netstat $pid\n";
}
else { # this is the "new" process
    system($netstat_cmd);
    exit();
}

sleep $seconds;

system "$stop_netstat_cmd";

(I don't have pskill, so you'll have to make that part work by yourself...)

Alex
  • 5,863
  • 2
  • 29
  • 46
0

Forks::Super makes this kind of task easy for you.

use Forks::Super;
fork { cmd => $netstat_cmd, timeout => $seconds };
wait;
mob
  • 117,087
  • 18
  • 149
  • 283