c - 秒到纳秒 - struct itimerspec

标签 c unix timer long-integer

我正在填充 timespec 结构。目的是,用户将始终以秒为单位输入值(也可以是 0.01 秒),因此我们使用以下方法将秒转换为纳秒:lt_leak_start = atoll(getenv("LT_LEAK_START")) * sec_to_nsec;其中变量 static long sec_to_nsec = 1000000000; 然后将其用作 settime 的参数:timer_settime(timerid,0,&its,NULL)。但是这样做会发生错误:settimer failed: Invalid argument

请帮帮我。

提前致谢。

enter code here
 struct timespec {            
    time_t tv_sec;    /* Seconds */            
    long   tv_nsec;  /* Nanoseconds */      
  };         

 struct itimerspec {            
   struct timespec it_interval;  /* Timer interval */            
   struct timespec it_value;     /* Initial expiration */        
 }; 

我正在尝试的代码在这里:

static long sec_to_nsec = 1000000000;
lt_leak_start = atoll(getenv("LT_LEAK_START")) * sec_to_nsec;

/* Setting timer interval */

its.it_interval.tv_sec=0;
its.it_interval.tv_nsec=1;

/* Setting timer expiration */

its.it_value.tv_sec=0;  // First expiry after 1 sec
its.it_value.tv_nsec=lt_leak_start;

timer_create(CLOCK_REALTIME,&sevp,&timerid);

if(timer_settime(timerid,0,&its,NULL)==-1) {
  perror("settimer failed");
  exit(1);
}

最佳答案

double d = strtod(getenv("LT_LEAK_START"), 0);
...
its.it_value.tv_sec=(time_t) d;
its.it_value.tv_nsec=(d - (time_t) d) * sec_to_nsec;

将环境变量读取为 double 值。将第二部分存储在 tv_sec 中,将纳秒部分存储在 tv_nsec 中。

关于c - 秒到纳秒 - struct itimerspec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5457489/

相关文章:

c - 海湾合作委员会 : linker error : undefined reference while using a constant data shared between two files

c - 在管道上使用 select 返回 10038

linux - 使用 pty(通过 ssh)和管道连接到更多时的阶梯式

.net - 我可以在其回调中放置Threading.Timer吗?

c# - 计时器已过事件不执行所有操作

c - 为 Linux 开发一个简单的窗口应用程序

c - 如何在预处理器#if 条件中捕获未定义的宏?

linux - 我如何将 tar 和 gzipped tar 组合成 gzipped tar?

linux - 使用模式将带有数字的字符串加 1

javascript - 如何让间隔定时器自动重新启动?