linux - clock_nanosleep 不返回 -1/set errno EINTR - LINUX

标签 linux multithreading unix posix clock

我是 Linux 新手。我正在尝试使用 clock_nanosleep 实现一个简单的任务。问题是,clock_nanosleep 在被信号中断后没有将 errno 设置为 EINTR。我试过重置 SA_RESTART 标志。但是,没有成功。这是我的代码。谢谢。

void signalHandler( int signum )
{
    printf("Interrupt signal received.\n");
}

void *periodic_thread (void *param)
{
struct itimerspec its;
struct sigevent sig;
struct timespec next, period;
sigset_t blocked;

siginfo_t si;
timer_t mytimer;
int i, j;

/* create a timer that will be used to periodically send a signal */
sig.sigev_notify = SIGEV_SIGNAL;
sig.sigev_signo = SIGUSR1;
sig.sigev_value.sival_ptr = &sig;

timer_create(CLOCK_REALTIME, &sig, &mytimer);

struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &signalHandler;
sigaction(SIGUSR1, &sa, NULL);

/* set the periodic timer */
its.it_value.tv_sec = 8;
its.it_value.tv_nsec = 00000000; 
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0; ;
period.tv_sec = 5;
period.tv_nsec = 00000000; 

timer_settime(mytimer, 0, &its, NULL); 

printf("periodic thread started...\n");

j=1;

i = clock_gettime(CLOCK_MONOTONIC, &next);
while(1)
{
  next.tv_sec = next.tv_sec + period.tv_sec;
  next.tv_nsec = next.tv_nsec + period.tv_nsec;
  i = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, 0);  
  printf("I am done \n");
  if((i == -1) && (errno == EINTR))
  break;
}

printf("...periodic thread end!\n");

timer_delete(mytimer);
return NULL;
}

int main()
{

  pthread_t mythread;
  pthread_attr_t myattr;

  //struct sched_param myparam;
  void *returnvalue;
  sigset_t blocked;


  /* initializes the thread attribute */
  pthread_attr_init(&myattr);


  printf("starting a periodic thread...\n");

  pthread_create(&mythread, &myattr, periodic_thread, NULL);

  pthread_attr_destroy(&myattr);

  /* wait the end of the thread we just created */
  pthread_join(mythread, &returnvalue);

  printf("ending main...\n");

return 0;
}

输出>>

  starting a periodic thread...
  periodic thread started...
  I am done 
  Interrupt signal received.
  I am done 
  I am done
  continues.. (Does not break the while(1)) 

最佳答案

我想通了,

问题:主线程被信号而不是包含 clock_nanosleep 的子线程中断。

解决方案 1:使用“pthread_sigmask(SIG_BLOCK, &blocked, NULL)”在主线程中阻止 SIGUSR1

解决方案 2:使用“sigev_notify = SIGEV_THREAD_ID”生成线程特定事件。 (适用于计时器)

谢谢

关于linux - clock_nanosleep 不返回 -1/set errno EINTR - LINUX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21542500/

相关文章:

用 libtasn1.h 编译 c

java - 具有执行程序或多线程环境的 Apache DBCP

linux - 尝试 grep 位置参数

Raspberry Pi 上的 Python 导入模块

linux - 如果在 xargs 中

Java谜题: busy wait threads stop working

java - 如何在 C# 和 Java 进程之间使用互斥体?

C/Cygwin : Porting htoll() from macOS/unix to Windows Cygwin

git - 如何捕获 `git clone` 的完整输出?

linux - 没有 X 的 Tegra Mesa GLES