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

I know multiple ways to run a program at shell, system(), exec(), ``, qx//.

But how do I run a program and allow mine to continue to execute?

For instance say my script has a list of media files and loops through them playing them with the program 'mplayer' I want to make it so that it calls the program, but then continues instead of waiting for the program to exit, as well I need to be able to kill the program directly from the script (ex: user types 'q' instead of menu option 'a')

--------------------------------------

I would rather take 30 minutes to re-invent the wheel then take 30 days to learn how to use someone else's. Before pestering me about my re-invention prepare to defend yourself with a way of learning how to use the wheel in less time than it takes for me to make one, one that I might add is specialized to my specific task!

  • Comment on Run a program and allow user to interactivly stop it.

Replies are listed 'Best First'.
Re: Run a program and allow user to interactivly stop it.
by mr_mischief (Monsignor) on Apr 07, 2008 at 20:59 UTC
    Well, on a sufficiently Unix-inspired system you could start the program in the background using the system's syntax for that. You could also fork() and exec(), then continue processing in the parent process.

    my $kid_pid = fork() or die "Cannot fork!\n"; exec( '/bin/ls' ) unless $kid_pid; my $keep_going = 1; while ( $keep_going ) { ... }

    See the fork info in perlfunc for more information.

Re: Run a program and allow user to interactivly stop it.
by ahmad (Hermit) on Apr 07, 2008 at 22:21 UTC

    To run a program an instantly return to your script

    you can use one of the following methods

    Linux:  system('myprog &');

    Windows:  system(1,'myprog');

Re: Run a program and allow user to interactivly stop it.
by zentara (Cardinal) on Apr 08, 2008 at 13:41 UTC
    To kill the spawned script from the parent, you need to get the pid of the forked process. Just one word of caution, sometimes, the pid returned is the bash shell pid of your process, so you sometimes need to deal with that issue of finding a pid with a parent pid of some value. In that case look at the Proc::Killfam module.

    If you are willing to go to an event-loop system,(GLib,POE,Tk,Gtk2,etc) many cool things are possible. See Readkey with timer using Glib for a Glib control loop, and Perl/Tk front-end to mplayer for some tricks on how to control mplayer.... you need to use it's slave mode.


    I'm not really a human, but I play one on earth. Cogito ergo sum a bum