我有一个问题要解决:我进程中的某个线程正在执行一个同步系统调用,我想立即中断它。为了解决这个问题,我可以通过 pthread_kill
发送一个信号,这会强制它返回 EINTR
。我制作了一段代码来说明这一点:
#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 个问题:
是否有其他选项可以中断另一个线程中的系统调用?
有没有办法避免在上面显示的方法中使用虚拟构造?
最佳答案
您可以在线程之间使用其他同步机制,但由于您想要中断阻塞的系统调用,我想不出有什么不同于 pthread_kill
的东西。
并且您需要使用显式的 signal_action
因为默认设置要么完全忽略信号(您不希望这样),要么中止整个程序(您不希望那个)。所以不,我无法想象有什么方法可以避免显式 signal_action
。
关于c - 系统调用中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26886954/