Program Club

C에서 nanosleep ()을 사용하는 방법?

proclub 2020. 10. 23. 19:40
반응형

C에서 nanosleep ()을 사용하는 방법? `tim.tv_sec`와`tim.tv_nsec`는 무엇인가요?


다음에서 tim.tv_sec의 용도는 무엇입니까 tim.tv_nsec?

500000마이크로 초 동안 실행을 어떻게 휴면 할 수 있습니까?

#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;
}

0.5 초는 500,000,000 나노초이므로 코드는 다음과 같아야합니다.

tim.tv_sec  = 0;
tim.tv_nsec = 500000000L;

현 상태에서 코드는 1.0000005 초 (1 초 + 500ns) 동안 잠자고 있습니다.


tv_nsec수면 시간 (나노초)입니다. 500000us = 500000000ns이므로 다음을 원합니다.

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

500000 마이크로 초는 500000000 나노초입니다. 500ns = 0.5µs 만 기다립니다.


나는 일반적으로 계산을 쉽게하기 위해 몇 가지 #define과 상수를 사용합니다.

#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 %d\n",ret);
   return 0;
}

POSIX 7

먼저 함수를 찾으십시오. http://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html

여기에는에 대한 링크가 포함 time.h되며, 헤더는 구조체가 정의 된 위치 여야합니다.

The header shall declare the timespec structure, which shall > include at least the following members:

time_t  tv_sec    Seconds. 
long    tv_nsec   Nanoseconds.

man 2 nanosleep

Pseudo-official glibc docs which you should always check for syscalls:

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */
};

More correct variant:

{
struct timespec delta = {5 /*secs*/, 135 /*nanosecs*/};
while (nanosleep(&delta, &delta));
}

참고URL : https://stackoverflow.com/questions/7684359/how-to-use-nanosleep-in-c-what-are-tim-tv-sec-and-tim-tv-nsec

반응형