Reputation: 1
I want to run service in PHP which to be run in the background. I have tried by using exec()
function in PHP but service is being run in infinite loop and control is not returning back over PHP file. I have searched more over the internet but I can't find the solution. Please give me some idea or reference to achieve this task.
This is code for reference what I want to do:-
echo"hello";
exec("raintree.frm");
echo"hello1";
raintree.frm
is a service which I want to execute. Here PHP script prints "hello" over browser but that is not coming on "hello1" because control gets stuck on exec()
function.
Upvotes: 0
Views: 10276
Reputation: 20015
You can make use of atd
for running arbitrary commands in a separate process:
shell_exec('echo code you want to run | at -m now');
For this, atd
should be installed and running, of course.
Upvotes: 1
Reputation: 2101
The exec()
function is waiting to receive the output of the externally executed command.
To prevent this from happening, you can redirect the output elsewhere:
<?php
echo 'hello1';
exec('raintree.frm > /dev/null &');
echo 'hello2';
This example will output "hello1hello2" without waiting for raintree.frm > /dev/null &
to finish.
(this probably only works with Unix-like operating systems)
Upvotes: -2
Reputation: 6968
If you'd like to have your service running in a separate process, as the title states, you need to create the new process and then run the service in it. In PHP you can create a new process with pcntl_fork()
and start the service in the child process. Something like this
echo "hello";
$pid = pcntl_fork();
switch($pid){
case -1: // pcntl_fork() failed
die('could not fork');
case 0: // you're in the new (child) process
exec("raintree.frm");
// controll goes further down ONLY if exec() fails
echo 'exec() failed';
default: // you're in the main (parent) process in which the script is running
echo "hello1";
}
For more clarification read the manual (the link above to pcntl_fork()
) as well as look at some C/Unix tutorials on the topics (or rather syscalls) fork()
and exec()
.
Upvotes: 4