data-id="1190000005056078" data-license="sa">
Use function
<code>pcntl_fork();//创建子进程 posix_setsid();//设置当前进程为进程组长 posix_getpid();//获取进程id</code>
Example
workerman Lieutenant General process
<code>/** * Run as deamon mode. * * @throws Exception */ protected static function daemonize() { if (!self::$daemonize) { return; } /** * 重设文件权限掩码 * 子进程从父进程继承了文件权限 * 若子进程不涉及到文件创建,可取消 */ umask(0); $pid = pcntl_fork();//创建子进程 if (-1 === $pid) { throw new Exception('fork fail'); } elseif ($pid > 0) { exit(0); //父进程退出 } /** * 更改子进程为进程组长 * 使子进程摆脱父进程控制 */ if (-1 === posix_setsid()) { throw new Exception("setsid fail"); } // Fork again avoid SVR4 system regain the control of terminal. $pid = pcntl_fork(); if (-1 === $pid) { throw new Exception("fork fail"); } elseif (0 !== $pid) { exit(0); } }</code>
Other instructions
Basic concept
Daemon process: background service process in Linux. It is a long-lived process that is usually independent of the controlling terminal and periodically performs some task or waits to handle certain events that occur. Daemons are often started when the system is booted and terminated when the system is shut down.
Process group: It is a collection of one or more processes. A process group is uniquely identified by a process group ID. In addition to the process number (PID), the process group ID is also a necessary attribute of a process. Each process group has a leader process, and the process number of the leader process is equal to the process group ID. And the process group ID will not be affected by the exit of the group leader process.
Session cycle: A session is a collection of one or more process groups. Usually, a session starts when the user logs in and ends when the user logs out. During this period, all processes run by the user belong to this session.
Create process
fork the child process, the parent process exits
Change the child process to the team leader process
Change the current directory to the root directory (chdir())
Reset file permission mask Code
Close the file descriptor
The daemon exits and handles the SIGCHLD signal
Signal processing
//TODO
References
PHP implements the daemon
The above introduces the workerman notes-php creation daemon process, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.