You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用execl()、fork()、kill()时无法接收信号的问题排查

问题分析与解决

核心问题1:Program1的kill语句无法执行

在子进程分支(id == 0)中,execl函数如果执行成功,会彻底替换当前子进程的内存空间,原Program1的后续代码(包括kill(id, SIGUSR1))会被完全覆盖,根本没有运行机会。只有当execl执行失败时(比如找不到program2可执行文件),kill才会触发,但此时子进程仍属于Program1,信号发送毫无意义。

核心问题2:Program2进程生命周期过短,无法接收信号

Program2注册完信号处理函数后,立刻执行return 0终止进程。即便此时有信号送达,进程已经退出,无法响应信号。

修复代码示例

修改后的Program1

#include <unistd.h>
#include <signal.h>
#include <stdio.h>

int main() {
    int id = fork();
    
    if (id == 0) {
        // 确保路径正确,这里假设program2在当前目录
        execl("./program2", "program2", NULL);
        perror("execl failed"); // 仅在execl失败时执行
        return 1;
    } else if (id > 0) {
        // 短暂等待,保证子进程完成信号注册
        sleep(1);
        // 父进程向子进程发送SIGUSR1信号
        kill(id, SIGUSR1);
    }
    return 0;
}

修改后的Program2

#include <stdio.h>
#include <signal.h>
#include <unistd.h>

void signal_handler1(int sig) {
    printf("test\n");
}

int main(int argc, char* argv[]) {
    signal(SIGUSR1, signal_handler1);
    printf("Hello world\n");

    // 暂停进程,等待信号触发
    while (1) {
        pause();
    }
}

修复后输出

Hello world
test

内容的提问来源于stack exchange,提问作者Kosky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 20:30:49