5

I have StartServer.php file that basically starts a server if it is not already started. Everything works perfect except that the StartServer.php will hang forever waiting for the shell_exec()'d file Server.php to finish its execution that it never does.

Is there a way to execute a PHP file and just forget about it -- and not wait for its execution to finish?

Edit: It has to work on Windows and Linux.

Tower
  • 98,741
  • 129
  • 357
  • 507
  • execute the file within an iFrame? or is it the server that hangs and not the browser? Are you running this script via a cron job? – Glycerine Sep 19 '10 at 11:16
  • This is purely server related question. A PHP script A wants to execute another PHP script B so that A finishes its execution while B never does. – Tower Sep 19 '10 at 11:17

3 Answers3

4

This should help you - Asynchronous shell exec in PHP

Basically, you shell_exec("php Server.php > /dev/null 2>/dev/null &")

Community
  • 1
  • 1
dekomote
  • 3,817
  • 1
  • 17
  • 13
  • As far as I know PHP doesn't have any kind of threading so you'll need to start a separate process. The details of that are always going to be platform specific. – Michael Clerx Sep 19 '10 at 12:07
0

You'll need something like the pcntl functions. Only problem is that this is a non-windows extension, and not suitable to run inside a web server. The only other possibility I can think of is to use the exec function and fork the current process manually (as suggested in dekomotes's answer), doing OS detection to figure out the command needed. Note that this approach isn't much different to using the pcntl functions (in Linux, at least) - the ampersand character causes the second script to be run inside different process. Multi-threaded / multi-process programming isn't well supported in PHP, particularly when running inside a web server.

Robin
  • 4,242
  • 1
  • 20
  • 20
0

I think it's traditional to let the server detach itself form the parent process, ie to "daemonize" itself, rather than having the script starting the server detach itself. Check the server you're starting to see if it has a daemon-option.

If you've written the server yourself, in PHP, you need to detach it. It looks somehting like this:

posix_setsid(); //Start a new session
if(pcntl_fork()) {exit();} //Fork process and kill the old one

I think this works on Windows too. (Not tested.)

0scar
  • 3,200
  • 25
  • 28