programing

C에서 nanosleep()을 사용하는 방법'tim.tv_sec'과 'tim.tv_nsec'이 뭐죠?

procenter 2022. 8. 17. 23:29
반응형

C에서 nanosleep()을 사용하는 방법'tim.tv_sec'과 'tim.tv_nsec'이 뭐죠?

의 용도는 무엇입니까?tim.tv_sec그리고.tim.tv_nsec다음 중 어느쪽이야?

sleeve 실행은 어떻게 하면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 나노초이므로 코드는 다음과 같습니다.

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

현 상태에서는 1.00005s(1s+500ns)의 sleep 상태가 됩니다.

tv_nsec수면 시간(나노초)입니다.500000us = 500000000ns이므로 다음 조건을 충족해야 합니다.

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

보다 정확한 변형:

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

이것은 나에게 효과가 있었다…

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


int mssleep(long miliseconds)
{
   struct timespec rem;
   struct timespec req= {
       (int)(miliseconds / 1000),     /* secs (Must be Non-Negative) */ 
       (miliseconds % 1000) * 1000000 /* nano (Must be in range of 0 to 999999999) */ 
   };

   return nanosleep(&req , &rem);
}

int main()
{
   int ret = mssleep(2500);
   printf("sleep result %d\n",ret);
   return 0;
}

POSIX 7

먼저 http://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html 기능을 찾습니다.

여기에는 에 대한 링크가 포함되어 있습니다.이 링크는 헤더로서 스트럭트가 정의되어 있어야 합니다.

헤더는 timespec 구조를 선언해야 하며 >는 적어도 다음 멤버를 포함해야 합니다.

time_t  tv_sec    Seconds. 
long    tv_nsec   Nanoseconds.

남자 2나노슬립

syscall을 항상 확인해야 하는 의사 공식 glibc 문서:

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

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);

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

반응형