php never ending loop

We have used the infinite loop in a live system environment to basically wait for incoming SMS and then process it. We found out that doing it this way makes the server resource intensive over time and had to restart the server in order to free up memory.

Another issue we encountered is when you execute a script with an infinite loop in your browser, even if you hit the stop button it will continue to run unless you restart Apache.

    while (1){ //infinite loop
    // write code to insert text to a file
    // The file size will still continue to grow 
    //even when you click 'stop' in your browser.
    }

The solution is to run the PHP script as a deamon on the command line. Here's how:

nohup php myscript.php &

the & puts your process in the background.

Not only we found this method to be less memory intensive but you can also kill it without restarting apache by running the following command :

kill processid

Edit: As Dagon pointed out, this is not really the true way of running PHP as a 'Daemon' but using the nohup command can be considered as the poor man's way of running a process as a daemon.

Tags:

Php

Loops