lighttpd cgi不能重启

1. 背景

cgi出现coredump后,lighttpd不能拉动cgi重启。

2. 重现问题

2.1. cgi实现

cpp 复制代码
/*! cgi简单实现 */
#include <stdio.h>
#include <fcgiapp.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, const char *argv)
{
    while (1) {
        FCGX_Request request = {0};
        FCGX_InitRequest(&request, 0, 0);
        FCGX_Accept_r(&request);
        system("sleep 100000000");
        FCGX_Finish_r(&request);
    }

    return 0;
}

2.2. 场景重现

bash 复制代码
# 运行lighttpd,此处将worker线程配置为4个
/smbdir/third_party/sbin/lighttpd -f /smbdir/third_party/lighttpd/etc/lighttpd.conf -D

# 手动kill掉cgi会出现cgi不能正常启动的问题
killall -11 cgi

3. 原因

lighttpd利用mod_facgi模块实现与cgi的交互,而cgi利用标准输入与lighttpd之间的信息互通,当在cgi中执行shell命令时,子进程会继承父进程的一些属性(标准输入也会被继承)。

3.1. lighttpd判断cgi是否正在运行

cpp 复制代码
    gw_fd = fdevent_socket_cloexec(proc->saddr->sa_family, SOCK_STREAM, 0);
    if (-1 == gw_fd) {
        log_perror(errh, __FILE__, __LINE__, "socket()");
        return -1;
    }

    do {
        status = connect(gw_fd, proc->saddr, proc->saddrlen);
        log_perror(errh, __FILE__, __LINE__, "status[%d], reason[%s], errno[%d]", status, strerror(errno), errno);
    } while (-1 == status && errno == EINTR);

    if (-1 == status && errno != ENOENT && proc->unixsocket) {
        log_perror(errh, __FILE__, __LINE__,
          "connect %s", proc->unixsocket->ptr);
        unlink(proc->unixsocket->ptr);
    }

    close(gw_fd);

如果此时cgi进程出现coredump,而由其产生的子进程由于继承了cgi的标准输入,会使上述connect系统调用正常返回0,从而导致lighttpd重启cgi进程失败

3.2. lighttpd重启cgi原理

cpp 复制代码
int status;

/*! lighttpd管理进程会在此处监听子进程状态,如果有子进程终止运行,则fdevent_waitpid_intr会返回 */
if (-1 != (pid = fdevent_waitpid_intr(-1, &status))) {
	log_monotonic_secs = server_monotonic_secs();
	log_epoch_secs = server_epoch_secs(srv);

    /*! 子进程终止运行后,该函数会最终调用gw_spawn_connection重启cgi进程 */
	if (plugins_call_handle_waitpid(srv, pid, status) != HANDLER_GO_ON) {
		if (!timer) alarm((timer = 5));
		continue;
	}
	switch (fdlog_pipes_waitpid_cb(pid)) {
	  default: break;
	  case -1: if (!timer) alarm((timer = 5));
		   __attribute_fallthrough__
	  case  1: continue;
	}
	/** 
	 * check if one of our workers went away
	 */
	for (int n = 0; n < npids; ++n) {
		if (pid == pids[n]) {
			pids[n] = -1;
			num_childs++;
			break;
		}
	}
}

4. 解决方案

自行封装形如popen或system类的接口,内部使用execl系列函数执行shell命令。但在执行命令前**优先关闭标准输入(close(0);)**即可解决该问题。

相关推荐
lihe75818 分钟前
每天凌晨3点自动同步UBUNTU源
linux·运维·ubuntu·本地源
添砖java‘’35 分钟前
线程的互斥与同步
linux·c++·操作系统·线程·信息与通信
凌寒111 小时前
minio预签名访问地址经过Nginx代理后返回403问题
服务器·网络·nginx
广然1 小时前
EVE-NG 镜像管理工具 1.1 Web 版本正式发布!
运维·服务器·前端
祁鱼鱼鱼鱼鱼1 小时前
DNS 笔记记录
运维·服务器·网络
tod1131 小时前
Makefile进阶(上)
linux·运维·服务器·windows·makefile·进程
阳光九叶草LXGZXJ1 小时前
达梦数据库-学习-50-分区表指定分区清理空洞率(交换分区方式)
linux·运维·数据库·sql·学习
Data_Journal1 小时前
【无标题】
大数据·服务器·前端·数据库·人工智能
zbliquan1 小时前
SS928v100远程ubuntu交叉编译开发环境搭建
linux·运维·ubuntu
我爱加班、、1 小时前
new Map()+Array.from()整理elementPlus的级联器数据
linux·前端·javascript