clock_nanosleep(): 它忽略 timespec 结构

clock_nanosleep(): It ignores timespec structure

我正在尝试创建这个基本的 clock_nanosleep 示例,但它不会暂停我的 for 循环,该循环继续打印数字。如果我取消注释 //t.tv_nsec = s/1000000000; 什么都不会打印,但是 for 循环将是 运行.

// POSIX.1-2017 is what compiler is confined to.
#define _XOPEN_SOURCE 700

// C headers.
#include <stdint.h>
#include <time.h>
#include <stdio.h>
   
int main(int argc, char *argv[])
{
    // Counter.
    uint8_t i;

    // Time.
    int s = 1;

    // Create a timespec structure and calculate it's members.
    struct timespec t;
    t.tv_sec = s;
    //t.tv_nsec = s/1000000000;

    // Set flags i.e. TIMER_ABSTIME to 0 to use relative instead of absolute time.
    int flags = 0;

    // Choose the clock i.e. CLOCK_MONOTONIC is a "clock_id" for the clock started at system start.
    int clock_id = CLOCK_MONOTONIC;

    for(i = 0; i < 256; i++){
        printf("%d", i);

        // Because last argument is NULL in case of error, remaining time is not stored in "t".
        clock_nanosleep(clock_id, flags, &t, NULL);
    }

    return 0;

}

我完全不知道为什么这不起作用。 POSIX 指出:

int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *rqtp, struct timespec *rmtp);

If the flag TIMER_ABSTIME is not set in the flags argument, the clock_nanosleep() function shall cause the current thread to be suspended from execution until either the time interval specified by the rqtp argument has elapsed, or a signal is delivered to the calling thread and its action is to invoke a signal-catching function, or the process is terminated.

我确定标志已归零。我设置了 rqtp&t.

The clock used to measure the time shall be the clock specified by clock_id.

我确实使用了CLOCK_MONOTONIC

If the clock_nanosleep() function returns because it has been interrupted by a signal, it shall return the corresponding error value. For the relative clock_nanosleep() function, if the rmtp argument is non NULL, the timespec structure referenced by it shall be updated to contain the amount of time remaining in the interval (the requested time minus the time actually slept). The rqtp and rmtp arguments can point to the same object. If the rmtp argument is NULL, the remaining time is not returned. The absolute clock_nanosleep() function has no effect on the structure referenced by rmtp.

我还将最后一个参数设置为NULL,以便在clock_naanosleep()被任何信号中断时不存储剩余时间。

那么为什么这不起作用?

在这种情况下,您应该 始终 检查实际的 return 值,在本例中为 EINVAL,因为 t.tv.nsec 未初始化。

使用:

struct timespec t = {
    .tv_sec = s,
};

正确初始化所有 字段,即使是您不打算使用的字段。

局部变量未隐式初始化。所以如果你不设置 t.tv_nsec 它可以包含任何值。如果该值恰好超出 0 - 999999999 范围,则 clock_nanosleep 将立即 return 并显示错误代码。

设置 t.tv_nsec 后看不到任何输出的原因是您的打印方式:

 printf("%d", i);

您没有在输出中包含换行符。 stdout 流是行缓冲的,因此它不会自动将输出流刷新到控制台。将 \n 添加到格式字符串的末尾,您将看到打印的行。