Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Running a process in the background

by Anonymous Monk
on Nov 23, 2004 at 21:59 UTC ( [id://409996]=perlquestion: print w/replies, xml ) Need Help??

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

Is there a way I can start a background process in perl?

I wanted to run two processes simultaneously hence I wanted to run one as the background process. The start command does not seem to help since I can't run another process till that is completed.

Any suggestions?

Replies are listed 'Best First'.
Re: Running a process in the background
by BrowserUk (Patriarch) on Nov 23, 2004 at 22:52 UTC

    The simplest method of doing this under Win32 is to put '1' as the first parameter to system.

    system 1, q[put the command to run in the background here]; ## The system command returns immediately. ## Do other things here.

    Qudos for bringing this undocumented feature to light goes to tye.


    Examine what is said, not who speaks.
    "But you should never overestimate the ingenuity of the sceptics to come up with a counter-argument." -Myles Allen
    "Think for yourself!" - Abigail        "Time is a poor substitute for thought"--theorbtwo         "Efficiency is intelligent laziness." -David Dunham
    "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
      IPC::Open2 and IPC::Open3 use system 1 on Windows, and fork elsewhere (as appropriate), so I usually recommend these.

        I have to disagree with that as a default recommendation for the OPs stated requirement.

        If you need the complexity of those--Ie. You need to be able to intereact with the background process's input and output streams--that is a fine recommendation, but for simply running a processes in the background?

        Neither is exactly the easiest of modules to use, and the documentation of both leaves a lot to be desired.

        That one reverses the order of the first two parameters relative to the other is confusing enough. I can never remember, or work out from the descriptions whether *RDRFH is a handle for reading, from the perspective of the perl script, or that of the command being run? I end up trying it to find out.

        That the descriptions are entirely geared to their use in a *nix environment, with most of the description being deferred to man page references and useage with *nix utilities, mean I would avoid recommending the use of either to a win32 user, without there being a definite need to do so.


        Examine what is said, not who speaks.
        "But you should never overestimate the ingenuity of the sceptics to come up with a counter-argument." -Myles Allen
        "Think for yourself!" - Abigail        "Time is a poor substitute for thought"--theorbtwo         "Efficiency is intelligent laziness." -David Dunham
        "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
Re: Running a process in the background
by osunderdog (Deacon) on Nov 23, 2004 at 22:21 UTC

    Since you are refering to the START command, I assume you are on windows. I believe that START /B will execute the command in the background.

    For example:

    start /b sleep 100

    Course this isn't the perl answer...


    "Look, Shiny Things!" is not a better business strategy than compatibility and reuse.


    OSUnderdog
      Hi osunderdog,

      Thanks for the suggestion. I tried doing start /b. The process does run in the background, but the next command (next process) is not executed till the background process finishes.

      What else do you suggest? Thanks.

Re: Running a process in the background
by tstock (Curate) on Nov 23, 2004 at 22:04 UTC
    You will need to fork a child process, so while that one is doing the "background" work, the parent can keep going.

    If you have several background processes to run at the same time, Parallel::ForkManager is good.

    Tiago
      Hello,

      Thanks for your response. Can you give me an example of how to use fork to start a function in a perl module in the background?

      Thank you.

        if (my $pid = fork) { # parent ($pid is process id of child) parent_function(); } else { # child child_function(); exit; }
        Feel free to read perldoc -f fork, and look at some examples online. This is not really advanced perl, but it requires some attention.
Re: Running a process in the background
by terra incognita (Pilgrim) on Nov 23, 2004 at 22:40 UTC
    What OS are you running?

    Under XP the start cmd will launch a separate cmd shell for each program you specify and then return to the calling cmd file.
    Are you calling start from a Perl script?
    Do you want the processes to return to the calling program (then you need threads).

    Some code would be great, so that we can understand exactly what you are doing.

      I am running Windows XP. Start does launch a separate cmd shell as you have mentioned.

      I am calling start from a perl script:

      my $output = `start /b perl test1.pl > testing.log`; test2();

      So basically I want test2() to run when test1.pl is executed in the background. But what really is happenning is that test1.pl completes its own commands and then test2() is executed.

      How can I make them run simulataneously? Thanks.

        I am running Windows XP.
        Ah, that changes things considerably. You could use the standard Unix, on Windows emulated approach, such as fork. But you can use Windows specific methods, too, such as using Win32::Process. See They didn't give me a fork so I have to eat with a spawn..

        As a variaton on that theme, I made a little module that, when used in a program, restarts the script with the same parameters, but without a console:

        # Save as module file Win32/Detached.pm, somewhere in @INC package Win32::Detached; use strict; use Win32; use Win32::Process; use Cwd; if(@ARGV and $ARGV[0] eq '-nolaunch') { shift; } elsif(!$^C) { Win32::Process::Create( my $ProcessObj, $^X, join(" ", map { tr/ // ? qq["$_"] : $_ } $^X, $0, "-nolaunch", + @ARGV), 0, DETACHED_PROCESS, cwd, ) or die Win32::FormatMessage(Win32::GetLastError()); exit; } 1;

        Simply do

        use Win32::Detached;
        in your main script, just making sure you don't use "-nolaunch" as a command line switch.

        If that module is not handy for you — to be honest, I've rarely ever used it — you can at least borrow the parameters for the API call.

        If you want to permanently run a perl script in the background, check out how to run a perl script as a service — for more detailed info, see also this online article.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://409996]
Approved by ysth
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2024-04-24 00:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found