MST

星途 面试题库

面试题:C语言中SIGTERM信号处理与程序资源清理

假设你正在开发一个多线程的C程序,该程序在收到SIGTERM信号时,不仅要安全地停止所有线程,还要正确释放所有动态分配的资源(如内存、文件描述符等)。请阐述整体的设计思路,并给出关键代码片段。
13.6万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

设计思路

  1. 信号处理函数:注册一个信号处理函数来捕获 SIGTERM 信号。在这个函数中,设置一个全局标志,表示程序需要终止。
  2. 线程协作:每个线程在运行过程中,需要定期检查这个全局标志。当标志被设置时,线程应有序地清理自己的工作并退出。
  3. 资源管理:对于动态分配的资源,每个线程负责释放自己分配的资源。主线程可以负责释放那些全局的动态资源,如打开的文件描述符等。

关键代码片段

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

// 全局标志,用于通知线程终止
volatile sig_atomic_t stop = 0;

// 模拟线程函数
void* thread_function(void* arg) {
    while (!stop) {
        // 线程工作
        printf("Thread is working...\n");
        sleep(1);
    }
    // 释放线程分配的资源,这里假设分配了内存
    int* data = (int*)arg;
    free(data);
    printf("Thread exiting...\n");
    return NULL;
}

// 信号处理函数
void sigterm_handler(int signum) {
    stop = 1;
    printf("Received SIGTERM, preparing to stop threads...\n");
}

int main() {
    pthread_t thread;
    int* data = (int*)malloc(sizeof(int));
    if (data == NULL) {
        perror("malloc");
        return 1;
    }

    // 注册信号处理函数
    struct sigaction sa;
    sa.sa_handler = sigterm_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction(SIGTERM, &sa, NULL);

    // 创建线程
    if (pthread_create(&thread, NULL, thread_function, data) != 0) {
        perror("pthread_create");
        free(data);
        return 1;
    }

    // 等待线程结束
    pthread_join(thread, NULL);

    // 主线程释放全局资源,这里假设打开了一个文件描述符
    FILE* file = fopen("test.txt", "r");
    if (file != NULL) {
        fclose(file);
    }

    printf("All threads stopped, resources released. Exiting...\n");
    return 0;
}