国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial Use PHP script to write Daemon program_PHP tutorial

Use PHP script to write Daemon program_PHP tutorial

Jul 21, 2016 pm 02:58 PM
php What use yes concept of program Script process

What is a Daemon process

This is another interesting concept. Daemon means "elf" in English, just like the ones we often see in Disney animations. Some can fly, some can't, and they often surround the protagonists of the cartoons. Wandering around, giving some advice, occasionally bumping into pillars unluckily, and sometimes coming up with some little tricks to save the protagonist from the enemy. Because of this, daemon is sometimes translated as "Guardian Saint". Therefore, the daemon process also has two translations in China. Some people translate it as "elf process" and some people translate it as "daemon process". Both of these terms appear frequently.

Similar to real daemons, daemon processes are also accustomed to hiding themselves from people's sight and silently contributing to the system. Sometimes people also call them "background service processes". The life of daemon processes is very long. Generally speaking, they will not exit from the moment they are executed until the entire system is shut down. Almost all server programs, including the well-known Apache and wu-FTP, are implemented in the form of daemon processes. For many common commands under Linux, such as inetd and ftpd, the letter d at the end refers to daemon.

Why must we use a daemon process? The interface for each system to communicate with users in Linux is called a terminal. Every process that starts running from this terminal will be attached to this terminal. This terminal is called these processes. The control terminal (Controlling terminal), when the control terminal is closed, the corresponding process will be automatically closed. Regarding this point, readers can try it with XTerm in X-Window. (Each XTerm is an open terminal.) We can start the application by typing commands, such as: $netscape Then we close the XTerm window and the netscape we just started The window will suddenly evaporate along with it. However, the daemon process can break through this limitation. Even if the corresponding terminal is closed, it can exist in the system for a long time. If we want a process to live for a long time, it will not be affected by user or terminal or other changes. If it is affected, this process must be turned into a daemon process.

Programming rules for Daemon processes

If we want to turn our process into a daemon process, we must strictly follow the following steps:

1. Call fork to generate a child process, and the parent process exits at the same time. All our subsequent work is done in the child process. To do this we can:

1.1 If we execute the program from the command line, this can create the illusion that the program has been executed, and the shell will go back and wait for the next command;

1.2 The new process just generated through fork will definitely not be the leader of a process group, which provides a prerequisite guarantee for the execution of step 2.

This will also cause a very interesting phenomenon: since the parent process has exited before the child process, the child process will have no parent process and become an orphan process (orphan). Whenever the system finds an orphan process, it will automatically be adopted by process No. 1. In this way, the original child process will become a child process of process No. 1.

2. Call the setsid system call. This is the most important step in the entire process. See appendix 2 for an introduction to setsid. Its function is to create a new session and serve as the session leader. If the calling process is the leader of a process group, the call will fail, but this was guaranteed in step 1. Calling setsid has three functions:

2.1 Let the process get rid of the control of the original session;

2.2 Let the process get rid of the control of the original process group;

2.3 Let the process get rid of the control of the original control terminal;

In short, it is to make the calling process completely independent and out of the control of all other processes.

3. Switch the current working directory to the root directory.

If we execute this process on a temporarily loaded file system, such as: /mnt/floppy/, the current working directory of the process will be /mnt/floppy/. The file system cannot be unmounted (umount) during the entire process, whether we are using this file system or not, this will bring us a lot of inconvenience. The solution is to use the chdir system call to change the current working directory to the root directory. No one will want to remove the root directory.

For the usage of chdir, see Appendix 1.

Of course, in this step, if there are special needs, we can also change the current working directory to another path, such as /tmp.

4. Set the file permission mask to 0.

This requires calling the system call umask, see Appendix 3. Each process inherits a file permission mask from the parent process. When a new file is created, this mask is used to set the default access permissions of the file and block certain permissions, such as write permissions for general users. When another process uses exec to call the daemon program we wrote, because we don't know what the file permission mask of that process is, it will cause some trouble when we create a new file. Therefore, we should reset the file permission mask. We can set it to any value we want, but generally, everyone sets it to 0, so that it will not block any user operations.

If your application does not involve creating new files or setting file access permissions at all, you can completely kick off the file permission mask and skip this step.

5. Close all unnecessary files.

Similar to the file permission mask, our new process will inherit some open files from the parent process. These opened files may never be read or written by our daemon process, but they still consume system resources and may cause the file system where they are located to be unable to be unmounted. It should be pointed out that the three files with file descriptors 0, 1 and 2 (the concept of file descriptors will be introduced in the next chapter), which are what we often call input, output and error files, also need to be closed. . It is likely that many readers will wonder about this, don’t we need input and output? But the fact is that after step 2 above, our daemon process has lost contact with the control terminal to which it belongs. It is impossible for the characters to reach the daemon process, and the characters output by the daemon process using conventional methods (such as printf) cannot be displayed on our terminal. Therefore, these three files have lost their existence value and should be closed.

Write Gearman’s Worker daemon using PHP

In my previous article, I introduced the use of Gearman. In my project, I use PHP to write a worker that runs all the time. If you follow the example recommended by Gearman and just wait for the task in a simple loop, there will be some problems, including: 1. When the code is modified, how to make the code modification take effect; 2. When restarting the Worker, how to ensure that the current Restart after the task processing is completed.

To address this problem, I have considered the following solutions:

1. After each code modification, the Worker needs to be restarted manually (kill first and then start). This only solves the problem of reloading the configuration file.

2. Set it in the Worker and restart the Worker after a single task cycle is completed. The problem with this solution is that it consumes a lot of money.

3. Add an exit function in the Worker. If the Worker needs to exit, send an exit call with a higher priority on the Client. This requires the cooperation of the client, which is not suitable when using background tasks.

4. Check whether the file has changed in the Worker. If it has changed, exit and restart itself.

5. Write signal control for Worker and accept restart instructions, similar to the http restart graceful instruction.

Finally, by combining methods 4 and 5, you can implement such a Daemon. If the configuration file changes, it will automatically restart; if it receives the user's kill -1 pid signal, it will also restart.

The code is as follows:

Copy to ClipboardLiehuo.Net Codes引用的內(nèi)容:[www.bkjia.com]
declare( ticks = 1 );
// This case will check the config file regularly, if the config file changed, it will restart it self
// If you want to restart the daemon gracefully, give it a HUP signal
// by shiqiang at 2011-12-04

$init_md5 = md5_file( 'config.php');

// register signal handler
pcntl_signal( SIGALRM, "signal_handler", true );
pcntl_signal( SIGHUP, 'signal_handler', TRUE );

$job_flag = FALSE; //Job status flag, to justify if the job has been finished
$signal_flag = FALSE; //Signal status flag, to justify whether we received the kill -1 signal

while( 1 ){
$job_flag = FALSE; //Job status flag
print "Worker start running ... n";
sleep(5);
print "Worker's task done ... n";
$flag = TRUE; //Job status flag
AutoStart( $signal_flag );
}

function signal_handler( $signal ) {
global $job_flag;
global $signal_flag;

switch( $signal ){
case SIGQUIT:
print date('y-m-d H:i:s', time() ) . " Caught Signal : SIGQUIT - No : $signal n";
exit(0);
break;
case SIGSTOP:
print date('y-m-d H:i:s', time() ) . " Caught Signal : SIGSTOP - No : $signal n";
break;
case SIGHUP:
print date('y-m-d H:i:s', time() ) . " Caught Signal : SIGHUP - No : $signal n";
if( $flag === TRUE ){
AutoStart( TRUE );
}else{
$signal_flag = TRUE;
}
break;
case SIGALRM:
print date('y-m-d H:i:s', time() ) . " Caught Signal : SIGALRM - No : $signal n";
//pcntl_exec( '/bin/ls' );
pcntl_alarm( 5 );
break;
default:
break;
}
}

function AutoStart( $signal = FALSE, $filename = 'config.php' ){
global $init_md5;

if( $signal || md5_file( $filename ) != $init_md5 ){
print "The config file has been changed, we are going to restart. n";
$pid = pcntl_fork();
if( $pid == -1 ){
print "Fork error n";
}else if( $pid > 0 ){
print "Parent exit n";
exit(0);
}else{
$init_md5 = md5_file( $filename );
print "Child continue to run n";
}
}
}

(本文來源:博客園,作者:小狼的世界)

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/363858.htmlTechArticle什么是Daemon進(jìn)程 這又是一個(gè)有趣的概念,daemon在英語中是精靈的意思,就像我們經(jīng)常在迪斯尼動畫里見到的那些,有些會飛,有些不會,經(jīng)...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

How to prevent session hijacking in PHP? How to prevent session hijacking in PHP? Jul 11, 2025 am 03:15 AM

To prevent session hijacking in PHP, the following measures need to be taken: 1. Use HTTPS to encrypt the transmission and set session.cookie_secure=1 in php.ini; 2. Set the security cookie attributes, including httponly, secure and samesite; 3. Call session_regenerate_id(true) when the user logs in or permissions change to change to change the SessionID; 4. Limit the Session life cycle, reasonably configure gc_maxlifetime and record the user's activity time; 5. Prohibit exposing the SessionID to the URL, and set session.use_only

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

PHP get the first N characters of a string PHP get the first N characters of a string Jul 11, 2025 am 03:17 AM

You can use substr() or mb_substr() to get the first N characters in PHP. The specific steps are as follows: 1. Use substr($string,0,N) to intercept the first N characters, which is suitable for ASCII characters and is simple and efficient; 2. When processing multi-byte characters (such as Chinese), mb_substr($string,0,N,'UTF-8'), and ensure that mbstring extension is enabled; 3. If the string contains HTML or whitespace characters, you should first use strip_tags() to remove the tags and trim() to clean the spaces, and then intercept them to ensure the results are clean.

How to URL encode a string in PHP with urlencode How to URL encode a string in PHP with urlencode Jul 11, 2025 am 03:22 AM

The urlencode() function is used to encode strings into URL-safe formats, where non-alphanumeric characters (except -, _, and .) are replaced with a percent sign followed by a two-digit hexadecimal number. For example, spaces are converted to signs, exclamation marks are converted to!, and Chinese characters are converted to their UTF-8 encoding form. When using, only the parameter values ??should be encoded, not the entire URL, to avoid damaging the URL structure. For other parts of the URL, such as path segments, the rawurlencode() function should be used, which converts the space to . When processing array parameters, you can use http_build_query() to automatically encode, or manually call urlencode() on each value to ensure safe transfer of data. just

PHP get the last N characters of a string PHP get the last N characters of a string Jul 11, 2025 am 03:17 AM

There are two main ways to get the last N characters of a string in PHP: 1. Use the substr() function to intercept through the negative starting position, which is suitable for single-byte characters; 2. Use the mb_substr() function to support multilingual and UTF-8 encoding to avoid truncating non-English characters; 3. Optionally determine whether the string length is sufficient to handle boundary situations; 4. It is not recommended to use strrev() substr() combination method because it is not safe and inefficient for multi-byte characters.

How to set and get session variables in PHP? How to set and get session variables in PHP? Jul 12, 2025 am 03:10 AM

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors

How to prevent SQL injection in PHP How to prevent SQL injection in PHP Jul 12, 2025 am 03:02 AM

Key methods to prevent SQL injection in PHP include: 1. Use preprocessing statements (such as PDO or MySQLi) to separate SQL code and data; 2. Turn off simulated preprocessing mode to ensure true preprocessing; 3. Filter and verify user input, such as using is_numeric() and filter_var(); 4. Avoid directly splicing SQL strings and use parameter binding instead; 5. Turn off error display in the production environment and record error logs. These measures comprehensively prevent the risk of SQL injection from mechanisms and details.

See all articles