php execute a background process

前端 未结 19 1447
萌比男神i
萌比男神i 2020-11-21 07:04

I need to execute a directory copy upon a user action, but the directories are quite large, so I would like to be able to perform such an action without the user being aware

19条回答
  •  我在风中等你
    2020-11-21 07:44

    Use this function to run your program in background. It cross-platform and fully customizable.

     is_string($redirectStdout) ? array('file', $redirectStdout, 'w') : array('pipe', 'w'),
            2 => is_string($redirectStderr) ? array('file', $redirectStderr, 'w') : array('pipe', 'w'),
        );
        if (is_string($stdin)) {
            $descriptorspec[0] = array('pipe', 'r');
        }
        $proc = proc_open($command, $descriptorspec, $pipes, $cwd, $env, $other_options);
        if (!is_resource($proc)) {
            throw new \Exception("Failed to start background process by command: $command");
        }
        if (is_string($stdin)) {
            fwrite($pipes[0], $stdin);
            fclose($pipes[0]);
        }
        if (!is_string($redirectStdout)) {
            fclose($pipes[1]);
        }
        if (!is_string($redirectStderr)) {
            fclose($pipes[2]);
        }
        return $proc;
    }
    

    Note that after command started, by default this function closes the stdin and stdout of running process. You can redirect process output into some file via $redirectStdout and $redirectStderr arguments.

    Note for windows users:
    You cannot redirect stdout/stderr to nul in the following manner:

    startBackgroundProcess('ping yandex.com', null, 'nul', 'nul');
    

    However, you can do this:

    startBackgroundProcess('ping yandex.com >nul 2>&1');
    

    Notes for *nix users:

    1) Use exec shell command if you want get actual PID:

    $proc = startBackgroundProcess('exec ping yandex.com -c 15', null, '/dev/null', '/dev/null');
    print_r(proc_get_status($proc));
    

    2) Use $stdin argument if you want to pass some data to the input of your program:

    startBackgroundProcess('cat > input.txt', "Hello world!\n");
    

提交回复
热议问题