views:

146

answers:

2

My problem is that when I run the following it will say that the bash script has finishes successfully. But it doesnt wait for the script to finish, if it quits to early it will move a file that it needs. So what am I doing wrong that it wont wait for the background process to finish to move the files?

my $pid = fork();
    if($pid == -1){
     die;
    } elsif ($pid == 0){
     #system(@autoDeploy) or die;
     logit("Running auto deploy for $bundleApp");
     exec("./deployer -d $domain.$enviro -e $enviro >> /tmp/$domain.$enviro &") 
                    or logit("Couldnt run the script.");
    }
    while (wait () != -1){

    }
    logit("Ran autoDeploy");

    logit("Moving $bundleApp, to $bundleDir/old/$bundleApp.$date.bundle");
    move("$bundleDir/$bundleApp", "$bundleDir/old/$bundleApp.$date.bundle");
    delete $curBundles{$bundleApp};
+1  A: 

You don't need to use & in your exec parameters, as you're already running under a fork.

Hasturkun
Does that still run in the background though? I see if I do that it will wait for the process.
Nerdatastic
Do you want to wait for the process or do you not want to wait for the process? If you don't want to wait for the process, why does your original code sample have a `wait` and why do you complain about the side-effects of that wait not working? Sounds like you want to wait to me...
hobbs
Yea I do thanks.
Nerdatastic
+4  A: 

The simplest thing that you're doing wrong is using & at the end of the exec commandline -- that means you're forking twice, and the process that you're waiting on will exit immediately.

I don't actually see what purpose fork/exec are serving you at all here, though, if you're not redirecting I/O and not doing anything but wait for the exec'd process to finish; that's what system is for.

system("./deployer -d $domain.$enviro -e $enviro >> /tmp/$domain.$enviro") 
                and logit("Problem running deployer: $?");

will easily serve to replace the first twelve lines of your code.

And just as a note in passing, fork doesn't return -1 on failure; it returns undef, so that whole check is entirely bogus.

hobbs
So system() all ready runs bash scripts in the background?
Nerdatastic
If you use `system` instead of `exec` in a child process, you probably want to explicitly call `exit` so the child doesn't rerun code that was just meant to be run in the parent process.
mobrule
@Nerdtastic - You called `fork` and then called `exec` (or `system`) in the child process, so yes, the command will run in the background.
mobrule
How would I go about modifying this to run for x amount of deploys?
Nerdatastic