3

I am using this code on Ubuntu 13.04,

$cmd = "sleep 20 &> /dev/null &";
exec($cmd, $output);

Although it actually sits there for 20 seconds and waits :/ usually it works fine when using & to send a process to the background, but on this machine php just won't do it :/
What could be causing this??

0

3 Answers 3

8

Try

<?PHP
$cmd = '/bin/sleep';
$args = array('20');

$pid=pcntl_fork();
if($pid==0)
{
  posix_setsid();
  pcntl_exec($cmd,$args,$_ENV);
  // child becomes the standalone detached process
}

echo "DONE\n";

I tested it for it works. Here you first fork the php process and then exceute your task.

Or if the pcntl module is not availabil use:

<?PHP

$cmd = "sleep 20 &> /dev/null &";
exec('/bin/bash -c "' . addslashes($cmd) . '"');
Sign up to request clarification or add additional context in comments.

9 Comments

always add a description of you answer.
CMD=> nohup sleep 20 &> /dev/null & This page was run in 20.082479000092 seconds array(0) { } didn't work :(
Changed my answer to a tested version.
the only problem is that it requires having a version of PHP compiled with pcntl enabled, which I don't :(
Changed my answer againe. Sorry but your solution is an bad idea because it is a realy huge securety lag.
|
1

The REASON this doesn't work is that exec() executes the string you're passing into it. Since & is interpreted by the shell as "execute in the background", but you don't execute a shell in your exec call, the & is just passed along with 20 to the /bin/sleep executable - which probably just ignores that.

The same applies to the redirection of output, since that is also parsed by the shell, not in exec.

So, you either need to find a way to fork your process (as described above), or a way to run the subprocess as a shell.

1 Comment

This is not true. exec() does launch a shell. One way you can detect the presence of the shell is by executing a command that the shell will consider invalid. For example, echo "<?php exec('NonExistentCommand'); ?>" | php will print something like "sh: NonExistentCommand: command not found". The sh: portion is coming from sh (/bin/sh)
0

My workaround to do this on ubuntu 13.04 with Apache2 and any version of PHP:
libssh2-php, I just used nohup $cmd & inside a local SSH session using PHP and it ran it just fine the background, of course this requires putting certain security protocols in place, such as enabling SSH access for the webserver user, so it would have exec-like permissions then only allowing localhost to login to the webserver ssh account.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.