【问题标题】:System call interruption系统调用中断
【发布时间】:2015-01-09 07:17:53
【问题描述】:

我有一个问题要解决:我的进程中的某个线程正在执行同步系统调用,我想立即中断它。为了解决这个问题,我可以通过pthread_kill 发送一个信号,这应该强制它返回EINTR。我做了一个sn-p代码来说明这一点:

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/select.h>
#include <unistd.h>

#define SIG SIGALRM

int work = 1;

void signal_action(int signal)
{
    fprintf(stderr, "%s caught\n", strsignal(signal));
}

void* thread_routine(void* arg)
{
    struct sigaction sa;
    sa.sa_handler = signal_action;

    if(sigaction(SIG, &sa, NULL) < 0)
    {
        fprintf(stderr, "sigaction failed with %d (%s)\n", errno, strerror(errno));
        return NULL;
    }

    fprintf(stderr, "Thread working\n");
    while(work)
    {
        int rc = select(0, NULL, NULL, NULL, NULL);
        if(rc < 0)
        {
            fprintf(stderr, "Select error: %d (%s)\n", errno, strerror(errno));
        }
        else
        {
            fprintf(stderr, "Select return %d\n", rc);
        }
    }
}

int main(int argc, char** argv)
{
    pthread_t handle;
    int rc = pthread_create(&handle, NULL, thread_routine, NULL);
    if(rc != 0)
    {
        fprintf(stderr, "pthread_create failed with %d (%s)\n", rc, strerror(rc));
        return 1;
    }

    sleep(1);

    work = 0;
    rc = pthread_kill(handle, SIG);
    if(rc != 0)
    {
        fprintf(stderr, "pthread_kill failed with %d (%s)\n", rc, strerror(rc));
        return 1;
    }

    rc = pthread_join(handle, NULL);
    if(rc != 0)
    {
        fprintf(stderr, "pthread_join failed with %d (%s)\n", rc, strerror(rc));
        return 1;
    }

    return 0;
}

但这让我定义了一个虚拟函数(signal_action),因为它不能以另一种方式工作。所以,2个问题:

  • 是否有其他选项可以中断另一个线程中的系统调用?

  • 有没有办法避免在上述方法中使用虚拟结构?

【问题讨论】:

    标签: c linux multithreading signals


    【解决方案1】:

    您可以在线程之间使用其他同步机制,但由于您想中断阻塞系统调用,我无法想象与pthread_kill 不同的东西。

    您需要使用显式的signal_action,因为默认设置是完全忽略信号(您不希望这样),或者中止整个程序(您也不希望那样)。所以不,我无法想象有一种方法可以避免明确的signal_action

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 2015-07-14
      • 2016-02-01
      • 2016-01-30
      • 2014-10-07
      相关资源
      最近更新 更多