Robert Lewis
Robert Lewis

Reputation: 1907

PHP exec command prevents echo from working

In this code:

session_write_close();
echo "reload";
flush();
//    exec("/etc/init.d/streaminit stop");
//    sleep(2);
//    session_write_close();
//    exec("/etc/init.d/streaminit start");
//    //all we have to do is copy currentView into nextView to trigger a page reload
//    sleep(2);

the echo of "reload" works, but if the lines below it are uncommented, nothing is echoed. I have tried many permutations of this and the conclusion is that the exec command is preventing the echo from working. I found some discussion of exec causing problems with Apache2, and one person said that session_write_close() might prevent the problem. Evidently in this case it doesn't. Are there any known fixes for this? Am I doing something wrong?

(streaminit is a shell script that starts and stops the mjpeg_streamer. The shell commands are asynchronous (with & at the end))

Upvotes: 1

Views: 286

Answers (1)

Robert Lewis
Robert Lewis

Reputation: 1907

I finally found this in the documentation for PHP's exec: "If a program is started with this function, in order for it to continue running in the background (my emphasis), the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends." The fix:

exec("/etc/init.d/streaminit stop > /dev/null 2>&1 &”);

For those unfamiliar (like me until a minute ago), this redirects the stdout device to /dev/null, and the 2>&1 means "send stderr output to the same place as stdout. Finally, the & means "run this command in the background". Works!

Upvotes: 2

Related Questions