在后台运行一个单独的进程来发送请求。即使您使用异步 http 请求(无论您使用什么语言),您仍然必须等待请求完成,然后才能退出脚本/程序。
PHP 不是 Java,每次 PHP 脚本执行完毕,所有资源都会被销毁,如果异步 http 请求还没有完成,则会被取消。
你可以考虑调用“nohup /path/your_script”来做一些后台任务。
提示:PHP打开的文件没有标记为FD_CLOEXEC,所以如果你有一个长时间运行的后台任务,你应该先关闭继承的文件描述符,否则会出现资源泄漏。
这是我用来帮助在 PHP 中运行后台任务的一些 C 代码:它首先关闭所有继承的文件描述符,将 stdout/stderr 重定向到 /dev/null,然后进入后台模式(如 nohup)
/*
gcc -m32 bgexec.c -o bgexec
*/
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
void close_fds()
{
char buf[256];
struct dirent *dp;
snprintf(buf, 255, "/proc/%i/fd/", getpid());
DIR *dir = opendir(buf);
while ((dp = readdir(dir)) != NULL) {
if(dp->d_name[0] && dp->d_name[0] != '.') {
//printf("fd: %s\n", dp->d_name);
close(atoi(dp->d_name));
}
}
closedir(dir);
}
int main(int argc, char *argv[])
{
int pid;
signal(SIGCLD, SIG_IGN); // no defunct when no wait();
if (argc < 2)
return fprintf(stderr, "No arguments given\n"), 1;
/* Fork it */
pid = fork();
if(pid < 0)
return fprintf(stderr, "Couldn't fork\n"), 127;
if (pid == 0) {
/* Child */
setsid();
umask ( 0 ); /* clear file mode creation mask */
close_fds();
int fd = open("/dev/null", O_RDWR);
dup2(0, 1);
dup2(0, 2);
signal(SIGHUP, SIG_IGN); // no hup
signal(SIGCLD, SIG_DFL); // keep away from 'exec' returns ECHILD
/* Execute it */
execv(argv[1], &argv[1]);
exit(127);
}
return 0;
}