[Origin] Everyone knows the daemon process (Daemon) under Linux/Unix, such as our commonly used httpd, mysqld, etc., which are programs running in resident memory, similar to services under Windows. Generally, daemon processes are written in C/C++, which is to generate child processes through fork. When the parent process under the current shell is killed, the child process will run in the background. In order not to generate output information on the terminal, functions such as syslog are used. to write log files.
We know that php is a scripting language and is executed through the php script engine, so it is troublesome to make a daemon process. Today we will combine Unix/Linux commands to realize the function of our daemon process.
[Principle] The function of the nohup command in Unix is to run the command without hanging up. At the same time, nohup puts all the output of the program into the nohup.out file in the current directory. If the file is not writable, it is placed in the <user home directory> /nohup.out file. So after having this command, our php program writes a shell script and uses a loop to keep our script running. Then, no matter whether our terminal window is closed or not, our php script can keep running. Of course, when our php process is killed or our operating system is restarted, it will naturally terminate.
[Function] You will definitely ask, what is the use of making our php script a daemon? Of course there are, such as the most typical function, which can basically replace the function of cron. For example, certain operations that we need to perform regularly can be done by it, and cron is no longer needed. Of course, if the server is restarted, there is no way. However, general Unix servers are not so easy to restart. In addition, we can also make a simple server-side function, such as making a server that can use Telnet. Hehe, it can be made into a small backdoor, but the implementation is a bit complicated.
[Practice] Example 1: Automatically generate files We will now do two examples to prove our above statement. First of all, the first one is to automatically generate a file every thirty seconds and execute it forever.
First, you must ensure that the operating system is Unix or Linux, such as FreeBSD, Redhat, Fedora or SUSE. Then we must ensure that our php script engine is in /usr/local/php/bin/php. The specific path can be written according to your actual path. If there is no script engine, please install it yourself.
For example, if the current directory is /home/heiyeluren/, then we use vi or other editors to write a file called php_daemon1.php:
$ vi php_daemon1.php
Then write the following code:
#!/usr/local/php/bin/php
<?
set_time_limit(0);
while(1)
{
@fopen("test_".time().".txt","w");
sleep(30);
}
?>
Then save and exit vi, and then give the php_daemon1.php file executable permissions:
$ chmod +x /home/heiyeluren/php_daemon1.php
Then let our script execute in the background and execute the following command:
$ nohup /home/heiyeluren/php_daemon1.php &
Remember to add the & symbol at the end so that it can run in the background. After executing the above command, the following prompt will appear:
[1] 82480
appending output to nohup.out
After returning to the car, a shell prompt will appear. So the above tip means that the output information of all command execution will be placed in the nohup.out file, which has been mentioned above. Then after executing the above command, we will see more files starting with test_ in the current directory every thirty seconds, such as: test_1139901144.txt test_1139901154.txt and other files, which proves that our program is running in the background .
So how do we terminate the running of the program? The best way is to restart the operating system. Haha, of course, this is not advisable. We can use the kill command to kill the process. Before killing the process, we naturally know the PID number of the process, which is the Process ID. You can use the ps command to see it. arrive.
$ps
PID TT STAT TIME COMMAND
82374 p3 Ss 0:00.14 -bash (bash)
82510 p3 S 0:00.06 /usr/local/php/bin/php /home/heiyeluren/php_daemon1.php
82528 p3 R+ 0:00.00 ps
Above we have seen that the process ID of our php is: 82510, so we execute the kill command:
$ kill -9 82510
[1]+ Killed nohup /home/heiyeluren/php_daemon1.php
When you see this prompt, you will know that the process has been killed. If you ps again, you will find that it is gone:
$ps
PID TT STAT TIME COMMAND
82374 p3 Ss 0:00.17 -bash (bash)
82535 p3 R+ 0:00.00 ps
If you cannot see the process directly with the ps command, then use the two combined ps & apos commands to view it, and you will definitely be able to see the process.
Based on the above process, you can expand the process to make your own cron program, then you don't need cron. Of course, this is just one way. Example 2: Server-side daemon. This example is related to the network. It is roughly simulated using PHP. server side, and then runs in the background to achieve the effect of server-side Daemon.
Continue in our home directory: /home/heiyeluren and edit the file php_daemon2.php:
$ vi php_daemon2.php
Enter the following code (the code is from the PHP manual, I have modified the comments):
#!/usr/local/php/bin/php
<?php
/* http://www.knowsky.com/php.asp settings do not display any errors*/
error_reporting(0);
/* The script timeout is infinite*/
set_time_limit(0);
/* Start fixed clearing */
ob_implicit_flush();
/* The IP of this machine and the ports that need to be opened */
$address = '192.168.0.1';
$port = 10000;
/* Generate a Socket */
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
echo "socket_create() failed: reason: " . socket_strerror($sock) . "n";
}
/* Bind the IP address and port */
if (($ret = socket_bind($sock, $address, $port)) < 0) {
echo “socket_bind() failed: reason: ” . socket_strerror($ret) . “n”;
}
/* Monitor Socket connection */
if (($ret = socket_listen($sock, 5)) < 0) {
echo “socket_listen() failed: reason: ” . socket_strerror($ret) . “n”;
}
/*Loop forever to monitor user connections*/
do {
if (($msgsock = socket_accept($sock)) < 0) {
echo "socket_accept() failed: reason: " . socket_strerror($msgsock) . "n";
break;
}
/* Send prompt information to connected users*/
$msg = “==========================================rn " .
"Welcome to the PHP Test Server. rnrn".
" To quit, type 'quit'. rn" .
"To shut down the server type 'shutdown'.rn" .
"To get help message type 'help'.rn" .
"==========================================rn" .
"php>";
socket_write($msgsock, $msg, strlen($msg));
do {
if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
echo “socket_read() failed: reason: ” . socket_strerror($ret) . “n”;
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
/*Close the client connection when the client enters the quit command*/
if ($buf == 'quit') {
break;
}
/* When the client enters the shutdown command, both the server and the client are shut down*/
if ($buf == 'shutdown') {
socket_close($msgsock);
break 2;
}
/* Output help information when the client enters the help command*/
if ($buf == 'help') {
$msg = “PHP Server Help Message rnrn”.
" To quit, type 'quit'. rn" .
"To shut down the server type 'shutdown'.rn" .
"To get help message type 'help'.rn" .
"php>";
socket_write($msgsock, $msg, strlen($msg));
continue;
}
/*Prompt message when the client input command does not exist*/
$talkback = “PHP: unknown command '$buf'.rnphp> “;
socket_write($msgsock, $talkback, strlen($talkback));
echo “$bufn”;
} while (true);
socket_close($msgsock);
} while (true);
/* Close Socket connection */
socket_close($sock);
?>
Save the above code and exit.
The above code roughly completes a function similar to the Telnet server side, that is, when the server side runs the program, the client can connect to the 10000 port of the server for communication.
Add executable permissions to the file:
$ chmod +x /home/heiyeluren/php_daemon2.php
Execute the command on the server:
$ nohup /home/heiyeluren/php_daemon2.php &
It enters the background operation, and we go up through the Windows client telnet:
C:>telnet 192.168.0.1 10000
If prompted:
Connecting to 192.168.0.188...Cannot open the connection to the host at port 10000: If the connection fails, it means that the server is not opened, or the above program is not executed correctly. Please check whether php has the –enable-sockets function. If prompted:
==========================================
Welcome to the PHP Test Server.
To quit, type 'quit'.
To shut down the server type 'shutdown'.
To get help message type 'help'.
==========================================
php>
This means that we have successfully connected to the server-side daemon written in PHP. After the php> prompt, we can execute three commands such as help, quit, and shutdown. If the command input is not these three, it will prompt:
php> asdf
PHP: unknown command 'asdf'.
Execute the help command to get help php> help
PHP Server Help Message
To quit, type 'quit'.
To shut down the server type 'shutdown'.
To get help message type 'help'.
This server side will not be introduced and can be expanded by yourself.
Killing the process is similar to example 1.
[Summary] Through the above learning, we know that PHP can also be used as a daemon process. If it is well designed, the function will be more powerful. However, we are just learning here and you can research and update it by yourself.
This article refers to the PHP Chinese manual. Reading more manuals will be very beneficial to you.