Cygwin:中断阻塞读取

时间:2015-01-10 21:19:19

标签: linux unix io cygwin signals

我编写了一个程序,它生成一个以阻塞的方式从stdin读取循环的线程。我想让线程立即从阻塞读取返回。我已经在读取线程中注册了我的信号处理程序(带有sigaction并且没有SA_RESTART标志),向它发送一个信号并期望读出以EINTR错误退出。但它不会发生。是Cygwin的问题还是限制,还是我做错了什么? 这是代码:

#include <stdio.h>
#include <errno.h>
#include <pthread.h>

pthread_t thread;
volatile int run = 0;
void root_handler(int signum)
{
    printf("%s ENTER (thread is %x)\n", __func__, pthread_self());
    run = 0;
}


void* thr_func(void*arg)
{  int res;
   char buffer[256];
   printf("%s ENTER (thread is %x)\n", __func__, pthread_self());
   struct sigaction act;
    memset (&act, 0, sizeof(act));
    act.sa_sigaction = &root_handler;
    //act.sa_flags = SA_RESTART;

    if (sigaction(SIGUSR1, &act, NULL) < 0) {
        perror ("sigaction error");
        return 1;
    }
   while(run)
   {
       res = read(0,buffer, sizeof(buffer));
       if(res == -1)
       {
          if(errno == EINTR)
          {
             puts("read was interrupted by signal");  
          }
       }
       else
       {
           printf("got: %s", buffer);
       }
   }
   printf("%s LEAVE (thread is %x)\n", __func__, pthread_self());
}

int main() {
    run = 1;
    printf("root thread: %x\n", pthread_self());

    pthread_create(&thread, NULL, &thr_func, NULL);
    printf("thread %x started\n", thread);
    sleep(4);
    pthread_kill(thread, SIGUSR1 );
    //raise(SIGUSR1);
    pthread_join(thread, NULL);
    return 0;
}

我正在使用Cygwin(1.7.32(0.274 / 5/3))。

1 个答案:

答案 0 :(得分:0)

我刚刚尝试在Ubuntu上做同样的事情并且它有效(我需要包含signal.h,尽管在Cygwin中它按原样编译)。这似乎是Cygwin实施的特殊性。