On Mon, Apr 13, 2009 at 04:49, Michael Alipio <daem0n...@yahoo.com> wrote:
snip
> my $pid = fork ();

You must check to see if $pid is defined.  If it isn't
then fork failed.  The parentheses are oddly placed and
unnecessary.

> if ($pid == 0){
>  exec ("top");

Again with the odd parentheses placement.  Function
calls should look like this

func($blah, $blah);

Control structures should look like this

while (1) {
if ($it_is_true) {

That space is one of the ways humans use to tell
function calls and control structures apart.

> }else{

There is no need to make this an else statement, exec
replaces the current process, so the child can never
reach the rest of the code

>   my $time = 0

You are missing a semi-colon at the end of this statement.

>   while (<1>){

You are trying to read from a non-existent filehandle
named 1, I assume you meant to say

while (1) {

to get an infinite loop.  This is also why your script
will never end: this while loop has no exit condition
and no calls to last in its body.

>     sleep 1;
>     $time++;
>     if ($time == 10){

Why all of this mess instead of a simple sleep 10?

>         kill 9, $pid;

SIGKILL is the kill of last resort, try SIGTERM instead.
It is also a good idea to reap the child with waitpid at
this point.  Right after this statement is where a call
to last should go.

>     }
>   }
> }

It might be a good idea to run "stty sane" to fix the
terminal (top leaves it in a bad state if killed).

#!/usr/bin/perl

use strict;
use warnings;

die "could not fork" unless defined(my $pid = fork);

if ($pid == 0) {
    exec "top";
    die "could not exec top";
}

sleep 3;

kill 15, $pid;
waitpid $pid, 0;

#fix the terminal after killing top
system "stty", "sane";

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to