Detailed explanation of writing daemon process for implementing system programming in PHP

不言
Release: 2023-03-23 16:56:01
Original
1278 people have browsed it

The content of this article is to share with you a detailed explanation of writing daemon processes in PHP system programming. It has a certain reference value. Friends in need can refer to it

(1)Process group, Concepts such as sessions, control terminals, and control processes

Process group: Each process has a process group (process group) to which it belongs, and the process group has a process group leader ( process group leader), the process group ID is the process number of the process group leader, so to determine whether a process is the process group leader, you only need to compare whether the process name is equal to its process group id. It can be used in PHP The function posix_getpgrp() obtains the process group ID of the current process, and posix_getpid() is used to obtain the process ID of the current process.


<?php

function isGroupLeader() {
    return posix_getpgrp() == posix_getpid();
}

$pid = pcntl_fork();

if($pid == 0) {
    echo &#39;子进程:&#39; . PHP_EOL;
}
elseif($pid > 0) {
    sleep(2);
    echo &#39;父进程:&#39; . PHP_EOL;
}

echo "当前进程组gid:" . posix_getpgrp() . PHP_EOL;
echo "当前进程号pid:" . posix_getpid() . PHP_EOL;

if (isGroupLeader()) {
    echo &#39;Is a process group leader&#39; . PHP_EOL;
}
else {
    echo &#39;Is not a process group leader&#39; . PHP_EOL;
}
Copy after login

The above routine will output:



##

子进程:
当前进程组gid:15827
当前进程号pid:15828
Is not a process group leader
父进程:
当前进程组gid:15827
当前进程号pid:15827
Is a process group leader
Copy after login

Session : A session is a collection of several process groups. One process group in the session is the session leader, and the session ID is the process group id of the session leader. You can use the function posix_getsid in PHP (int $pid) to get the session ID of the specified process, or you can use the function posix_setsid() to create a new session. At this time, the process becomes the session leader of the new session. The function call successfully returns the newly created session ID. Or return -1 when an error occurs. Note that posix_setsid() is called in Linux The process of the function cannot be the process group leader, otherwise the call will fail. This is because a process in a process group cannot span multiple sessions at the same time.


Document introduction about setsid in Linux:


setsid()  creates  a  new  session  if  the calling process is not a process group leader.  The calling process is the leader of the new session, the process group
       leader of the new process group, and has no controlling tty.  The process group ID and session ID of the calling process are set to the PID of the calling process.
       The calling process will be the only process in this new process group and in this new session.
Copy after login
<?php

function isGroupLeader() {
    return posix_getpgrp() == posix_getpid();
}

echo "当前会话id: " . posix_getsid(0) . PHP_EOL; //传0表示获取当前进程的会话id

if (isGroupLeader()) {
    echo "当前进程是进程组长\n";
}

$ret = posix_setsid();  //创建一个新会话
var_dump($ret);  //由于当前进程是进程组长,此处会返回-1, 表示调用失败
Copy after login

The above routine will output:



当前会话id: 13000
当前进程是进程组长
int(-1)
Copy after login

How to create a new session? We noticed that after using pcntl_fork() to create a child process, the child process is not the process leader. , so you can use child processes to create new sessions.


##

<?php
function isGroupLeader()
{
     return posix_getpgrp() == posix_getpid();
}
echo "当前进程所属会话ID:" . posix_getsid(0) . PHP_EOL;

$pid = pcntl_fork();

if ($pid > 0) {
    exit(0); // 让父进程退出
}
elseif ($pid == 0) {
    if (isGroupLeader()) {
        echo "是进程组组长\n";
    } else {
        echo "不是进程组组长\n";
    }
    echo "进程组ID:" . posix_getpgrp() . PHP_EOL;  
    echo "进程号pid: " . posix_getpid() . PHP_EOL;

    $ret = posix_setsid();
    var_dump($ret);

    echo "当前进程所属会话ID:" . posix_getsid(0) . PHP_EOL;
}
Copy after login

The above routine will output:


当前进程所属会话ID:13000
[root@localhost php]# 不是进程组组长
进程组ID:15856
进程号pid: 15857
int(15857)
当前进程所属会话ID:15857
Copy after login

A new session was successfully created using the child process.



Control terminal and Control process: (Terminal is the general term for all input and output devices, such as keyboard, mouse, and monitor are all a terminal) A session There can be one control terminal, and one control terminal is exclusive to one session. When a session is first created, there is no control terminal, but the session leader can apply to open a terminal. If this terminal is not the control terminal of other sessions, the terminal at this time will become the control terminal of the session. The session leader is called the control process.


To determine whether a session has a control terminal under Linux, we can try to open a special file /dev/tty, which points to the real control terminal Terminal, if it is opened successfully, it means that you have a control terminal, otherwise, there is no control terminal.

<?php
function isGroupLeader()
{
     return posix_getpgrp() == posix_getpid();
}

$pid = pcntl_fork();

if ($pid > 0) {
        sleep(1);
        $fp = fopen("/dev/tty", "rb");
        if ($fp) {
            echo "父进程会话 " . posix_getsid(0) . " 拥有控制终端\n";
        } else {
            echo "父进程会话 " . posix_getsid(0) . " 不拥有控制终端\n";
        }

    exit(0); // 让父进程退出
}
elseif ($pid == 0) {
    if (isGroupLeader()) {
        echo "是进程组组长\n";
    } else {
        echo "不是进程组组长\n";
    }

    $ret = posix_setsid();
    var_dump($ret);

    $fp = fopen("/dev/tty", "rb");
    if ($fp) {
            echo "子进程会话 " . posix_getsid(0) . " 拥有控制终端\n";
    }   else {
            echo "子进程会话 " . posix_getsid(0) . " 不拥有控制终端\n";
    }
}
Copy after login

The child process of the above routine creates a new session, and then both the parent and child processes try to open the file /dev/tty. The output of the routine is as follows:


不是进程组组长
int(15906)
PHP Warning:  fopen(/dev/tty): failed to open stream: No such device or address in /root/php/setsid.php on line 30

Warning: fopen(/dev/tty): failed to open stream: No such device or address in /root/php/setsid.php on line 30
子进程会话 15906 不拥有控制终端
父进程会话 13000 拥有控制终端
Copy after login

Generate SIGHUP signal

1. When a session loses control of the terminal, the kernel will send control to the session The process sends a SIGHUP signal, and usually the controlling process of the session is the shell process. When the shell receives a SIGHUP signal, it will also send a SIGHUP signal to all process groups (foreground or background process groups) created by it, and then exit. The default processing method when a process receives a SIGHUP signal is to exit the process. Of course, the process can also customize signal processing or ignore it.

2. In addition, when the control process terminates, the kernel will also send a SIGHUP signal to all members of the terminal's foreground process group.

<?php
$callback = function($signo){
        $sigstr = &#39;unkown signal&#39;;
        switch($signo) {
        case SIGINT:
            $sigstr = &#39;SIGINT&#39;;
            break;
        case SIGHUP:
            $sigstr = &#39;SIGHUP&#39;;
            break;
        case SIGTSTP:
            $sigstr = &#39;SIGTSTP&#39;;
            break;
        }
       file_put_contents("daemon.txt", "catch signal $sigstr\n", FILE_APPEND);
};

pcntl_signal(SIGINT, $callback);
pcntl_signal(SIGHUP, $callback);
pcntl_signal(SIGTSTP, $callback);

while(1)
{
    sleep(100);
    pcntl_signal_dispatch();
}
Copy after login

Use php sighup.php to run the program, then close the terminal directly, log in to the shell again, you will find that the program is still running, and the daemon.txt file will Log the captured SIGHUP signal.

[root@localhost php]# cat daemon.txt 
catch signal SIGHUP
[root@localhost php]# ps aux | grep sighup.php 
root     18438  0.0  0.4 191600  8996 ?        S    16:48   0:00 php sighup.php
root     18443  0.0  0.0 103328   896 pts/0    S+   16:53   0:00 grep sighup.php
Copy after login

At the same time, Linux provides a nohup command, which allows the process to ignore all SIGHUP signals, such as

[root@localhost php]# nohup php sighup.php 
nohup: 忽略输入并把输出追加到"nohup.out"
Copy after login

(2)
Standard input, standard output, standard error output
There are three default open file handles STDIN and STDOUT in php, STDERR corresponds to the above three file descriptors respectively. Since standard input and output are related to the terminal, it is of no use to the daemon process. It can be closed directly, but closing it directly may cause a problem. Please see the following code.

<?php
fclose(STDOUT);

$fp = fopen("stdout.log", "a");

echo "hello world\n";
Copy after login

When running the above code, the screen will not output echo information, but will be written to the open file. This is because after closing the STDOUT file handle, it is released The corresponding file descriptor is obtained, and Linux always uses the smallest available file descriptor to open a file, so this file descriptor now points to the file opened by fopen, causing the information originally written to the standard output to be now written to the file. In order to avoid this weird behavior, we can immediately open the black hole file /dev/null provided by Linux after closing these three file handles, such as:

<?php
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
fopen(&#39;/dev/null&#39;, &#39;r&#39;);
fopen(&#39;/dev/null&#39;, &#39;w&#39;);
fopen(&#39;/dev/null&#39;, &#39;w&#39;);

$fp = fopen("stdout.log", "a");

echo "hello world\n";
Copy after login

上面这个例程关闭STDIN,STDOUT, STDERR立马打开 /dev/null 三次,这样echo的信息会直接写到黑洞中,避免了前面出现的怪异的问题。


(三)编写守护进程涉及的其他问题

编写守护进程还涉及工作目录、文件掩码、信号处理、热更新、安全的启动停止等等问题,这里先留给大家自己百度,后期有空再来补充。


(四)一个守护进程的示例

<?php

//由于进程组长无法创建会话,fork一个子进程并让父进程退出,以便可以创建新会话
switch(pcntl_fork()) {
    case -1:
            exit("fork error");
            break;
    case 0: 
            break;
    default:
            exit(0); //父进程退出
}

posix_setsid();  //创建新会话,脱离原来的控制终端

//再次fork并让父进程退出, 子进程不再是会话首进程,让其永远无法打开一个控制终端
switch(pcntl_fork()) {
    case -1:
        exit("fork error");
        break;
    case 0:
        break;
    default:
        exit(0); //父进程退出
}

//关闭标准输入输出
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
fopen(&#39;/dev/null&#39;, &#39;r&#39;);
fopen(&#39;/dev/null&#39;, &#39;w&#39;);
fopen(&#39;/dev/null&#39;, &#39;w&#39;);

//切换工作目录
chdir(&#39;/&#39;);

//清除文件掩码
umask(0);

//由于内核不会再为进程产生SIGHUP信号,我们可以使用该信号来实现热重启
pcntl_signal(SIGHUP, function($signo){
    //重新加载配置文件,重新打开日志文件等等
});

for(;;)
{
     pcntl_signal_dispatch();  //处理信号回调
    //实现业务逻辑
}
Copy after login



to be continue!

相关推荐:

PHP实现系统编程之网络Socket及IO多路复用

PHP实现系统编程之本地套接字(Unix Domain Socket)

PHP实现系统编程之 多进程编程介绍及孤儿进程、僵尸进程




The above is the detailed content of Detailed explanation of writing daemon process for implementing system programming in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!