【问题标题】:PHP Non blocking http requestPHP 非阻塞 http 请求
【发布时间】:2019-01-10 07:45:17
【问题描述】:

在 PHP 中,我正在为我正在从事的项目构建一个挂钩系统。 如果触发钩子,系统将在数据库中检查需要执行的外部文件。

为了实现这一点,我正在考虑使用 curl,唯一的问题是 curl 阻止了其余代码的执行。我想要的只是向给定的 URL 发送一个 HTTP 请求,而根本不必等待响应。我们不在乎状态。由客户确保代码正常工作。

最大的挑战是我们仍然使用 PHP 5.5.9 :( 所以在我们升级到 PHP 7.2 之前,解决方案应该可以使用它

有什么想法或推动实现这一目标?

【问题讨论】:

  • Async curl request in PHP的可能重复
  • 在后台运行一个单独的进程来发送请求。即使您使用异步 http 请求(无论您使用什么语言),您仍然必须等待请求完成才能退出脚本/程序。
  • 先升级你的PHP。 5.5 停止获得安全修复 两年半前!如果我是你的客户,我不会和你做生意。
  • @BartFriederichs 告诉我,如果你能说服项目经理,那就太好了,这不再是了:P
  • 可能有不升级的原因,但如果这是一项公开可用的服务,则没有。

标签: php httprequest php-5.5


【解决方案1】:

在后台运行一个单独的进程来发送请求。即使您使用异步 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;
}

【讨论】:

    猜你喜欢
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多