Detailed explanation of PHP program daemonization examples

小云云
Release: 2023-03-21 21:52:02
Original
1132 people have browsed it

Generally, Server programs run in the background of the system, which is very different from ordinary interactive command line programs. There is a function daemon in glibc. Calling this function can cause the current process to leave the terminal and become a daemon process. For details, see man daemon. There is currently no such function in PHP. Of course, if you are interested, you can write a PHP extension function to implement it.

There are two ways to implement daemonization of PHP command line programs:

1. Use nohup

nohup php myprog.php > log.txt &
Copy after login

Daemonization is achieved here.

Execute php myprog.php alone. When ctrl+c is pressed, program execution will be interrupted and the current process and child processes will be killed.

php myprog.php &, although the executing program is also run in the background, it actually depends on the terminal. When the user exits the terminal, the process will be killed.

2. Use PHP code to implement

function daemonize()
{$pid = pcntl_fork();if ($pid == -1)
{die("fork(1) failed!\n");
}elseif ($pid > 0)
{//让由用户启动的进程退出exit(0);
}//建立一个有别于终端的新session以脱离终端posix_setsid();$pid = pcntl_fork();if ($pid == -1)
{die("fork(2) failed!\n");
}elseif ($pid > 0)
{//父进程退出, 剩下子进程成为最终的独立进程exit(0);
}
}daemonize();sleep(1000);
Copy after login

Use the above code to implement daemonization. When your PHP program needs to run in the background, you only need to call the encapsulated function once Just daemonize().
Note: Redirection of standard input and output is not implemented here.

Related recommendations:

PHP program daemonization

The above is the detailed content of Detailed explanation of PHP program daemonization examples. 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!