PHP protects Linux/Unix processes

Source: Internet
Author: User
Tags php server
[Origin] Daemon in linuxUnix is known to all. for example, httpd and MySQLd are commonly used, which are programs running in the resident memory, similar to services in Windows. Generally, the daemon processes are written using CC ++, that is, the child process is generated through fork. the parent process under the current shell is killed, and the child process is transferred to the background for running, in order not to generate output information on the terminal, syslog and other functions are used to write log files. [Origin] Daemon in linux/Unix is known to all. for example, httpd and MySQLd are commonly used, which are programs running in resident memory, similar to services in Windows. Generally, the Daemon process is written in C/C ++, that is, the child process is generated through fork. the parent process under the current shell is killed, and the child process runs in the background, in order not to generate output information on the terminal, syslog and other functions are used to write log files.
We know that php is a scripting language and is executed through the php script engine. Therefore, it is troublesome to make a daemon process, today, we will use Unix/Linux commands to implement the functions of our daemon process.
[Principle] the nohup command in Unix is used to run the command without hanging up. at the same time, nohup puts all output of the program to the nohup in the current directory. out File. if the file cannot be written, put it in <用户主目录> /Nohup. out file. With this command, our php program will write the shell script and use the loop to keep our script running. no matter whether the terminal window is closed or not, make our php scripts run all the time. Of course, when our php process is killed or our operating system is restarted, it will naturally stop.
[Function] I will certainly ask, what is the use of our php script as a daemon process? Of course, for example, the most typical function can basically replace cron functions. for example, some operations that we need to perform on a regular basis can be handed over to it, and cron is no longer needed. of course, there is no way to restart the server. However, the Unix server is not so easy to restart. In addition, we can also provide a simple server-side function, such as a server capable of Telnet, which can be used as a small backdoor, but this implementation is a little complicated.
[Practice] Example 1: automatic file generation
Let's take two examples to prove our above statement. The first one is to automatically generate a file every thirty seconds and keep running forever.
First, make sure 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, install it on your own.
For example, if the current directory is/home/heiyeluren/, we can use vi or another editor to compile a file named 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 );
}
?>
Save and exit vi, and then grant the executable permission to the php_daemon1.php file:
$ Chmod + x/home/heiyeluren/php_daemon1.php
Then let's run the script in the background and execute the following command:
$ Nohup/home/heiyeluren/php_daemon1.php &
Remember to add the & symbol to the end so that you can run it in the background. the following prompt appears after executing the preceding command:
[1] 82480
Appending output to nohup. out
A shell prompt will appear after you return to the car. The above prompt means that all output information for command execution will be put in the nohup. out file, which has been mentioned above. 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 so on, this proves that our program has been run in the background.
So how do we terminate the program? The best way is to restart the operating system. Oh, of course, this is not desirable. we can use the kill command to kill the process. before killing the process, we will naturally know the PID of the process, it is the PRocess ID. you can see it by using the ps command.
$ Ps
PID TT STAT TIME COMMAND
82374 p3 Ss. 14-bash (bash)
82510 p3 S. 06/usr/local/php/bin/php/home/heiyeluren/php_daemon1.php
82528 p3 R +. 00 ps
As we have seen above, the php process id is 82510, so we can execute the kill command:
$ Kill-9 82510
[1] + Killed nohup/home/heiyeluren/php_daemon1.php
When you see this prompt, you will understand that this process has been killed, and then ps will find that there is no more:
$ Ps
PID TT STAT TIME COMMAND
82374 p3 Ss. 17-bash (bash)
82535 p3 R +. 00 ps
If the process cannot be viewed through the ps command, you can use the ps & apos command to view the process.
On the basis of the above process extension, you can build your own cron program, then you don't need cron. of course, this is just a way Example 2: The server-side daemon process
This example is related to the network. it is generally used to simulate the use of php on the server side, and then run in the background to achieve the Daemon effect on the server side.
In our home directory:/home/heiyeluren, edit the php_daemon2.php file:
$ Vi php_daemon2.php
Enter the following code (the code is from the PHP manual and I have modified and commented on it ):
#! /Usr/local/php/bin/php
   /* Http://www.cncms.com/php.asp settings do not display any errors */
Error_reporting (0 );
/* The script times out infinitely */
Set_time_limit (0 );
/* Start fixed cleanup */
Ob_implicit_flush ();
/* Local ip address and port to be opened */
$ Address = '1970. 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 ";
}

/* Listen for Socket connection */
If ($ ret = socket_listen ($ sock, 5) <0 ){
Echo "socket_listen () failed: reason:". socket_strerror ($ ret). "\ n ";
}
/* Always-cycle monitoring accepts user connections */
Do {
If ($ msgsock = socket_accept ($ sock) <0 ){
Echo "socket_accept () failed: reason:". socket_strerror ($ msgsock). "\ n ";
Break;
}
/* Send a prompt to the connected user */
$ Msg = "=============================================== =======\ r \ n ".
"Welcome to the PHP Test Server. \ r \ n ".
"To quit, type 'quit'. \ r \ n ".
"To shut down the server type 'shutdown '. \ r \ n ".
"To get help message type 'HELP'. \ r \ n ".
"======================================================== ===\ R \ n ".
"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 client are closed */
If ($ buf = 'shutdown '){
Socket_close ($ msgsock );
Break 2;
}
/* The client outputs help information when entering the help command */
If ($ buf = 'help '){
$ Msg = "PHP Server Help Message \ r \ n ".
"To quit, type 'quit'. \ r \ n ".
"To shut down the server type 'shutdown '. \ r \ n ".
"To get help message type 'HELP'. \ r \ n ".
"Php>";
Socket_write ($ msgsock, $ msg, strlen ($ msg ));
Continue;
}
/* Message displayed when the command entered by the client does not exist */
$ Talkback = "PHP: unknow command '$ buf'. \ r \ nphp>";
Socket_write ($ msgsock, $ talkback, strlen ($ talkback ));
Echo "$ buf \ n ";
} While (true );
Socket_close ($ msgsock );
} While (true );
/* Close the Socket connection */
Socket_close ($ sock );
?>
Save the preceding code and exit.
The above code roughly completes a function similar to the Telnet server, that is, when the server runs the program, the client can connect to port 10000 of the server for communication.
Add the executable permissions of the file:
$ Chmod + x/home/heiyeluren/php_daemon2.php
Run the following command on the server:
$ Nohup/home/heiyeluren/php_daemon2.php &
The system runs in the background. We use the Windows client to telnet:
C: \> telnet 192.168.0.1 10000
If the prompt is:
Connecting to 192.168.0.188... The connection to the host cannot be opened. in port 10000, the connection fails.
This indicates that the server is not enabled or the preceding program is not correctly executed. check whether php-enable-sockets is enabled. If the prompt is:
========================================================== =
Welcome to the PHP Test Server.
To quit, type 'quit '.
To shut down the server type 'shutdown '.
To get help message type 'help '.
========================================================== =
Php>
It means that the server-side daemon process written in PHP is successfully connected, and three commands such as help, quit, and shutdown can be executed at the end of the php> prompt, if not, the following message is displayed:
Php> asdf
PHP: unknow command 'asdf '.
Run the help command to obtain 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 is not introduced and can be expanded on its own.
The kill process is similar to the example.
[Conclusion] through the above learning, we know that php can also be used as a daemon process. if the design is good, the function will be quite powerful. However, we only want to learn it here. we can study and update it on our own.
This article has referred to the php Chinese manual. it is very helpful to read more manual.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.