Running daemon from PHP

For a website, I need to start and stop the daemon process. What I'm doing now is

exec("sudo /etc/init.d/daemonToStart start"); 

The daemon process is running, but Apache / PHP freezes. Running ps aux showed that sudo itself has become a zombie process, effectively killing all further successes. Is this normal behavior when trying to start daeomon from PHP?

And yes, Apache has the right to run the command /etc/init.d/daemonToStart . I modified the / etc / sudoers file so that it does. No, I did not allow Apache to execute any command, just a few to make the site work.

In any case, returning to my question, is there a way to allow PHP to run daemons in such a way that a zombie process is not created? I ask about this because when I do the opposite, stopping the already running daemon, it works fine.

+8
php daemon zombie-process
source share
3 answers

Try adding > /dev/null 2>&1 & to the command.

So this is:

 exec("sudo /etc/init.d/daemonToStart > /dev/null 2>&1 &"); 

Just in case you want to know what he is doing / why:

  • > /dev/null - redirect STDOUT to / dev / null (black hole, in other words)
  • 2>&1 - redirect STDERR to STDOUT (black hole also)
  • & detach a process and run it in the background
+10
source share

I had the same problem.

I agree with DaveRandom, you need to suppress every output (stdout and stderr). But there is no need to start in another process with the ending " & ": the exec () function can no longer check the return code and returns ok, even if there is an error ...

And I prefer to store the outputs in a temporary file rather than a blackhole'it. Working solution:

 $temp = tempnam(sys_get_temp_dir(), 'php'); exec('sudo /etc/init.d/daemonToStart >'.$temp.' 2>&1'); 

Just read the contents of the file after and delete the temporary file:

 $output = explode("\n", file_get_contents($temp)); @unlink($temp); 
+2
source share

I never tried to run the daemon from PHP, but I tried to run other shell commands, with great difficulty. Here are some things I've tried in the past:

  • According to DaveRandom's answer, add /dev/null 2>&1 & at the end of your command. This will redirect errors to standard output. Then you can use this output for debugging.
  • Make sure the user of your PATH web server contains all referenced binaries inside your script daemon. You can do this by calling exec('echo $PATH; whoami;) . This will say that the user is running PHP, and the current PATH variable.
0
source share

All Articles