# posix - POSIX - 在C中，如何使用nanosleep() 什么是`tim.tv_sec`和`tim.tv_nsec`？

``````
#include <stdio.h>

#include <time.h>

int main()

{

struct timespec tim, tim2;

tim.tv_sec = 1;

tim.tv_nsec = 500;

if(nanosleep(&tim , &tim2) < 0 )

{

printf("Nano sleep system call failed n");

return -1;

}

printf("Nano sleep successfull n");

return 0;

}

``````

``````
tim.tv_sec = 0;

tim.tv_nsec = 500000000L;

``````

`tv_nsec`是以纳秒为单位的睡眠时间，500000us =500000000ns，所以你想：

``````
nanosleep((const struct timespec[]){{0, 500000000L}}, NULL);

``````

``````
#define NANO_SECOND_MULTIPLIER 1000000 // 1 millisecond = 1,000,000 Nanoseconds

const long INTERVAL_MS = 500 * NANO_SECOND_MULTIPLIER;

``````

``````
timespec sleepValue = {0};

sleepValue.tv_nsec = INTERVAL_MS;

nanosleep(&sleepValue, NULL);

``````

``````
#include <stdio.h>

#include <time.h> /* Needed for struct timespec */

int nsleep(long miliseconds)

{

struct timespec req, rem;

if(miliseconds > 999)

{

req.tv_sec = (int)(miliseconds / 1000); /* Must be Non-Negative */

req.tv_nsec = (miliseconds - ((long)req.tv_sec * 1000)) * 1000000; /* Must be in range of 0 to 999999999 */

}

else

{

req.tv_sec = 0; /* Must be Non-Negative */

req.tv_nsec = miliseconds * 1000000; /* Must be in range of 0 to 999999999 */

}

return nanosleep(&req , &rem);

}

int main()

{

int ret = nsleep(2500);

printf("sleep result %dn",ret);

return 0;

}

``````

``````
{

struct timespec delta = {5 /*secs*/, 135 /*nanosecs*/};

while (nanosleep(&delta, &delta));

}

``````