Home >Backend Development >PHP Problem >Is php single process or multi-process?

Is php single process or multi-process?

(*-*)浩
(*-*)浩Original
2019-09-29 10:39:316034browse

Writing a PHP multi-process program is actually as simple as putting an elephant in the refrigerator with a few steps.

Is php single process or multi-process?

PHP implements multi-process in three simple steps: Create sub-processes, manage sub-processes, and process sub-processes. It sounds simple, but it involves a lot of knowledge. For example, you need to know that each process has a process number (pid), and you also need to know how the command line executes php files. (Recommended learning: PHP video tutorial)

php multi-process requires pcntl and posix extension support, which can be viewed through php -m.

In the first step to create a child process, the pcntl_fork() function is used. The function return value is usually 0, and -1 is returned on failure. Let me first give you an intuitive example of creating a child process:

    $ppid = posix_getpid();
    $pid = pcntl_fork();
    if ($pid == -1) {
        throw new Exception('fork子进程失败!');
    } elseif ($pid > 0) {
        cli_set_process_title("我是父进程,我的进程id是{$ppid}.");
     sleep(30); // 保持30秒,确保能被ps查到
    } else {
        $cpid = posix_getpid();
        cli_set_process_title("我是{$ppid}的子进程,我的进程id是{$cpid}.");
        sleep(30);
    }

The second step of managing child processes uses signals. To put it simply, the parent process uses two functions pcntl_signal() and pcntl_signal_dispatch, which are responsible for installing signal processors and distributing work to the child process. This step will be briefly introduced first, because it involves the concept of a callback function, and I will add more comprehensive content in the future.

The third step of processing the child process also requires two functions. One is the posix_kill() function that sends a termination signal, and the other is the pcntl_waitpid() function that waits for the status of the child process, so that the purpose of completing the task together with the child process can be achieved.

So, back-end development is like this. Many things that you think will be complicated are actually very clear steps. Basically, they require a lot of knowledge but not many functions. So when you get started, just bite the bullet and learn it, and believe that one day you will be able to understand it clearly.

The above is the detailed content of Is php single process or multi-process?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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