अपने प्रोग्राम को पृष्ठभूमि में चलाने के लिए इस फ़ंक्शन का उपयोग करें। यह क्रॉस-प्लेटफॉर्म और पूरी तरह से अनुकूलन योग्य है।
<?php
function startBackgroundProcess(
$command,
$stdin = null,
$redirectStdout = null,
$redirectStderr = null,
$cwd = null,
$env = null,
$other_options = null
) {
$descriptorspec = array(
1 => 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;
}
ध्यान दें कि कमांड शुरू होने के बाद, डिफ़ॉल्ट रूप से यह फ़ंक्शन रनिंग प्रक्रिया की गति और गति को बंद कर देता है। आप $ redirectStdout और $ redirectStderr तर्कों के माध्यम से कुछ फ़ाइल में प्रोसेस आउटपुट को रीडायरेक्ट कर सकते हैं।
विंडोज उपयोगकर्ताओं के लिए ध्यान दें:
आप nulनिम्नलिखित तरीके से stdout / stderr को पुनर्निर्देशित नहीं कर सकते हैं :
startBackgroundProcess('ping yandex.com', null, 'nul', 'nul');
हालाँकि, आप ऐसा कर सकते हैं:
startBackgroundProcess('ping yandex.com >nul 2>&1');
* निक्स उपयोगकर्ताओं के लिए नोट्स:
1) यदि आप वास्तविक पीआईडी प्राप्त करना चाहते हैं, तो निष्पादन शेल कमांड का उपयोग करें:
$proc = startBackgroundProcess('exec ping yandex.com -c 15', null, '/dev/null', '/dev/null');
print_r(proc_get_status($proc));
2) यदि आप अपने प्रोग्राम के इनपुट में कुछ डेटा पास करना चाहते हैं, तो $ stdin तर्क का उपयोग करें:
startBackgroundProcess('cat > input.txt', "Hello world!\n");