Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

this is the code ive written so far! i would be grateful if somebody could show me how to stop it spawning off a heap of processes.
#!/usr/local/bin/perl -w for(;;) #repeat forever { print "please enter a command\n"; $cmd = <STDIN>; #get input from keyboard chomp ($cmd); #remove carriage return if ($cmd =~/^q$/i) #if cmd is quit { exit; #exit from program } else { if (fork== 0) #child process created { exec $cmd; #execute the command } wait; #wait for child process to terminate } }

Edit by tye
Edit by neshura

Replies are listed 'Best First'.
Re: simple perl2
by Beatnik (Parson) on Jun 18, 2001 at 21:02 UTC
    The infinite loop does have that nasty side effect :)

    Try a last to end it...
    exit merely stops the process, in a way it breaks the loop too :)

    Greetz
    Beatnik
    ... Quidquid perl dictum sit, altum viditur.
Re: simple perl2
by virtualsue (Vicar) on Jun 18, 2001 at 23:49 UTC
    I have a few suggestions:
    1. You should take your fork/exec logic out of that infinite loop. If you are ending up with "heaps of processes" the loop is the main reason why.
    2. I think blindly exec-ing something from ‹STDIN› is a very bad idea. Maybe you're the only one who'll be using that program, but if I were you I'd want to examine $cmd before running it. This might be a place where taint mode would be useful.
    3. Don't leave a child process hanging about if the exec failed:   exec $cmd or die;
Re: simple perl2
by DrZaius (Monk) on Jun 18, 2001 at 22:11 UTC
    Try out Term::ReadLine. It will give you nice interface instead of $cmd = <STDIN>;.

    You get ctrl-(\w), as well as a command buffer that is searchable. Well, you basically get GNU Readline :)

    Oh yeah, don't forget to use strict :)