很多,很久以前我寫在通過輪詢接收指令的服務器的客戶端系統的後臺不斷地跑了PHP後臺程序,然後進行各種文件I/O操作作爲迴應。對於它的價值,下面是允許這作爲一個守護進程運行的代碼的相關部分,即後臺PHP程序:
// (Note:
// The writeLog() function has been set up previously and is a
// trivial function that adds timestamped lines into a logfile.)
$PIDfile='/tmp/myPID'; // Store process ID in this file
// If a deamon is already running, display its PID and abort:
if (file_exists ($PIDfile)) {
if (is_readable ($PIDfile))
die ($PIDfile . " already exists, PID=" .
file_get_contents ($PIDfile) . " (stale PID file?)\n");
else
die ($PIDfile . " already exists, but is not readable.\n");
}
// Set execution directives if we're running a PHP version prior to 5.3.0
// (ticks are deprecated as of PHP5.3.0 and will be removed from PHP6.0.0):
if (version_compare (PHP_VERSION, '5.3.0', '<'))
declare (ticks = 1);
// Fork off the background (daemon) process:
$pid = pcntl_fork();
if ($pid == -1) {
die ("Fatal: unable to fork.\n");
} elseif ($pid)
exit(); // We are the parent process
// If we arrive at this point, we are the child process.
// Detach from the controlling terminal:
if (posix_setsid() == -1)
die ("Fatal: unable to detach from terminal.\n");
// Register child PID:
$posid = posix_getpid();
$fp = fopen ($PIDfile, "w");
fwrite ($fp, $posid);
fclose ($fp);
// Set up signal handlers:
pcntl_signal (SIGTERM, "SIGhandler");
pcntl_signal (SIGHUP, "SIGhandler");
// Log successful deamonization:
writeLog ("Daemon spawned, PID = " . $posid);
// Daemon payload code starts here:
while (1) {
// Do all kinds of interesting stuff that does not require any user
// input or screen output. In my case this consisted of file I/O and
// communication with a server using various sockets.
}
// EOF
希望這有助於!不用說,以上是從我的代碼太平間複製和粘貼的歲月東西,並提供沒有任何保證或擔保。請享用!
您可以使用[Ajax](https://www.w3schools.com/xml/ajax_intro.asp)。 –
後臺進程需要由網頁瀏覽器啓動?它是否需要在Web服務器重新啓動後才能生存?它需要跨平臺(Unix和Windows)嗎? –
嗨,是使用Windows,通過瀏覽器啓動.. 表單提交 - >在服務器上運行後臺php腳本以靜默模式「窗口」 - >獲取進程ID - >後臺腳本stil運行在服務器上的靜默模式。 –