0

In my php script I generate a sequence of console commands to be executed. The sequence is strict because each next command relies on the result of the previous command. I use ';' delimiter between commands.

Under normal circumstances I just exec() that sequence and it works fine. But sometimes I need this sequence to be niced and run in background. I read that one command can be run in background by appending ' > /dev/null &' to it. But with a sequence I tried different approaches but to no avail. I feel that exec() might not be the right function for the job.

How can this be done? As far as I understand I need to prepend each command with 'nice -n 10 '.

UPDATE1:

The code I'm currently using:

$cmd[] = '...';
//...
$cmd[] = '...';
//...

if($inBackground)
{
    foreach($cmd as &$command)
        $command = 'nice -n 10 '.$command.' > /dev/null ';
}

if($inBackground)
    exec(implode(' ; ', $cmd).' &');
else
    exec(implode(' ; ', $cmd));

UPDATE2:

I changed the code using the tip from mario and now it works:

$cmd[] = '...';
//...
$cmd[] = '...';
//..

$command = implode(' ; ', $cmd);
if($inBackground)
    $command = "nice sh -c '".$command."' > /dev/null &";

exec($command);

I made sure that my commands are properly escaped and don't contain single quotes.

0 Answers0