Programming

C에서 밀리 초로 대체 슬립 기능이 있습니까?

procodes 2020. 7. 19. 17:15
반응형

C에서 밀리 초로 대체 슬립 기능이 있습니까?


Windows에서 컴파일 된 소스 코드가 있습니다. Red Hat Linux에서 실행되도록 변환하고 있습니다.

소스 코드에는 <windows.h>헤더 파일 이 포함되어 있으며 프로그래머는이 Sleep()함수를 사용하여 밀리 초 동안 기다렸습니다. Linux에서는 작동하지 않습니다.

그러나 sleep(seconds)함수를 사용할 수 는 있지만 초 단위의 정수를 사용합니다. 밀리 초를 초로 변환하고 싶지 않습니다. Linux에서 gcc 컴파일과 함께 사용할 수있는 대체 절전 기능이 있습니까?


예-이전 POSIX 표준이 정의 usleep()되었으므로 Linux에서 사용할 수 있습니다.

   int usleep(useconds_t usec);

기술

usleep () 함수는 (적어도) usec 마이크로 초 동안 호출 스레드의 실행을 일시 중단합니다. 시스템 활동이나 호출 처리에 소요 된 시간 또는 시스템 타이머 단위로 인해 절전 시간이 약간 길어질 수 있습니다.

usleep()마이크로 초가 걸리므 로 밀리 초 단위로 절전 모드로 전환하려면 입력에 1000을 곱해야합니다.


usleep()이후 더 이상 사용되지 않으며 POSIX에서 제거되었습니다. 새 코드의 경우 nanosleep()선호됩니다.

   #include <time.h>

   int nanosleep(const struct timespec *req, struct timespec *rem);

기술

nanosleep()최소한 지정된 시간 *req이 경과하거나 호출 스레드에서 핸들러 호출을 트리거하거나 프로세스를 종료하는 신호 전달이 완료 될 때까지 호출 스레드 실행을 일시 중단합니다 .

구조 timespec은 나노초 정밀도로 시간 간격을 지정하는 데 사용됩니다. 다음과 같이 정의됩니다.

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

신호로 중단 된 경우 절전 모드를 계속 msleep()사용하여 구현 된 예제 함수 nanosleep():

int msleep(long msec)
{
    struct timespec ts;
    int res;

    if (msec < 0)
    {
        errno = EINVAL;
        return -1;
    }

    ts.tv_sec = msec / 1000;
    ts.tv_nsec = (msec % 1000) * 1000000;

    do {
        res = nanosleep(&ts, &ts);
    } while (res && errno == EINTR);

    return res;
}

이 크로스 플랫폼 기능을 사용할 수 있습니다 :

#ifdef WIN32
#include <windows.h>
#elif _POSIX_C_SOURCE >= 199309L
#include <time.h>   // for nanosleep
#else
#include <unistd.h> // for usleep
#endif

void sleep_ms(int milliseconds) // cross-platform sleep function
{
#ifdef WIN32
    Sleep(milliseconds);
#elif _POSIX_C_SOURCE >= 199309L
    struct timespec ts;
    ts.tv_sec = milliseconds / 1000;
    ts.tv_nsec = (milliseconds % 1000) * 1000000;
    nanosleep(&ts, NULL);
#else
    usleep(milliseconds * 1000);
#endif
}

다른 방법에 usleep()(이 POSIX 2004 년까지 정의하지만, 그것은 POSIX 준수의 역사를 가진 리눅스와 다른 플랫폼에서 분명히 볼 수 있습니다) POSIX 2008 년에 정의되지 않은, POSIX의 2008 표준을 정의 nanosleep():

nanosleep -고해상도 수면

#include <time.h>
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);

The 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 to terminate the process. The suspension time may be longer than requested because the argument value is rounded up to an integer multiple of the sleep resolution or because of the scheduling of other activity by the system. But, except for the case of being interrupted by a signal, the suspension time shall not be less than the time specified by rqtp, as measured by the system clock CLOCK_REALTIME.

The use of the nanosleep() function has no effect on the action or blockage of any signal.


Beyond usleep, the humble select with NULL file descriptor sets will let you pause with microsecond precision, and without the risk of SIGALRM complications.

sigtimedwait and sigwaitinfo offer similar behavior.


#include <unistd.h>

int usleep(useconds_t useconds); //pass in microseconds

#include <stdio.h>
#include <stdlib.h>
int main () {

puts("Program Will Sleep For 2 Seconds");

system("sleep 2");      // works for linux systems


return 0;
}

참고URL : https://stackoverflow.com/questions/1157209/is-there-an-alternative-sleep-function-in-c-to-milliseconds

반응형