0

I was wondering. If you have a PHP request and the PHP code calls a command line tool via exec..

Is the command line then processed in another thread than the one the PHP script is running under?

And if so are both shared over more than one core?

2
  • 2
    Was just about to answer when I noticed clarkk's comment... Commented Aug 9, 2016 at 19:25
  • @obe just flag the comment Commented Aug 9, 2016 at 19:28

1 Answer 1

1

As the manual suggests:

If a program is started with this function, in order for it to continue running in the background, 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.

This might give you an idea that the process is not forked and runs on the main thread. PHP actually waits for the output to end and get the last line of the log.

However, there is a way to run your command in background:

nohup MY_COMMAND > /dev/null 2>&1 & echo $!

Since exec receives the value of the last line of the output, this will return the pid of the process and you will be able to kill it later on.


Also, as N.B. mentioned in a comment, you may use fastcgi_finish_request() function if you use fpm - FastCGI Process Manager.

That function gives the client an answer without stopping the script execution. For instance, this is how you send an e-mail without fpm:

mail($recipient, 'Subject', 'Hello, Kitty!');
echo 'Okay, we sent the e-mail';

And this is how you may send an email with fpm:

echo 'Okay, we sent the e-mail';
fastcgi_finish_request();
mail($recipient, 'Subject', 'Hello, Kitty!');

In this case the client will get the echoed text and the mail function will still run in the background.

Just do not forget to close your sessions with session_write_close(); before you use fpm ;)

Sign up to request clarification or add additional context in comments.

1 Comment

There's also fastcgi_finish_request() available for php-fpm users, which sends the response back to server and everything after that function continues to run in the background (sort of). Any chance you could mention it in your answer? I don't want to pollute the thread with yet another answer that contains only this information.

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.