tonykang22 / study

0 stars 0 forks source link

[리눅스 개발환경] 14. 시간 #85

Open tonykang22 opened 2 years ago

tonykang22 commented 2 years ago

14. 시간

시간 개요


리눅스 시스템의 기원 시간


리눅스에서 시간을 나타내는 자료구조





현재 시간 획득

#include <time.h> 

time_t time (time_t *t);


int main() { printf("time returned: %ld\n", (long)time(NULL)); return 0; }


<br><br>

### 현재 시간 획득 (마이크로 초)
``` c
#include <sys/time.h>

int gettimeofday (struct timeval *tv, struct timezone *tz);



int main() { struct timeval tv; int ret;

ret = gettimeofday(&tv, NULL); 
if (ret == -1) {
    perror("gettimeofday error: ");
    return -1; 
}

printf("seconds = %ld, useconds = %ld\n", (long)tv.tv_sec, (long)tv.tv_usec); 

}


<br><br>

### 현재 시간 획득 (나노 초)
``` c
#include <time.h>

int clock_gettime (clockid_t clock_id, struct timespec *ts);


현재 시간 설정

#include <time.h> 

int stime (time_t *t);


#include <sys/time.h>

int settimeofday (const struct timeval *tv, const struct timezone *tz);


#include <time.h>

int clock_settime (clockid_t clock_id, const struct timespec *ts);



시간 유틸리티

#include <time.h>

char * ctime (const time_t *timep);
char * ctime_r (const time_t *timep, char *buf);


int main() { time_t t = time(NULL); printf("time: %s", ctime(&t)); return 0; }


<br><br>

- `_r 계열 함수`들의 의미는?
     * 재진입 함수(Reentrancy)를 의미한다.
- 초기 POSIX.1에 기반한 C 함수들은 단일 스레드 프로세스 환경을 가정하고 만들어졌다.
- 멀티스레드 환경에서 재진입 가능한지 여부를 보장할 수 없다.
    * 스레드 내에서 재진입이 불가능한 함수 호출 시 인자 데이터 내용을 변경한다든지 하여 결과값의 정합성을 보장하지 못하기 때문이다.
- 재진입 불가능한 함수 
    * 예: asctime(), gmtime(), ctime(), localtime() 등
- 이 문제를 해결하기 위해 _r이 붙은 별도의 함수 지정 
    * 예: asctime_r(), gmtime_r(), ctime_r(), localtime_r()

<br>

``` c
#include <time.h>

struct tm * gmtime (const time_t *timep);
struct tm * gmtime_r (const time_t *timep, struct tm *result);

struct tm * localtime (const time_t *timep);
strcut tm * localtime_r (const time_t *timep, struct tm *result);


double difftime (time_t time1, time_t time0);



#include <stdio.h> 
#include <time.h>

int main()
{
    time_t t = time(NULL); 
    struct tm *tm1, *tm2;

    tm1 = gmtime(&t); 
    tm2 = localtime(&t); 
    if (!tm1 || !tm2) {
        perror("gmtime, localtime error: ");
        return -1; 
    }

    printf("%d %d %d %d:%d:%d\n", tm1->tm_year+1900, tm1->tm_mon+1, tm1->tm_mday, tm1->tm_hour, tm1->tm_min, tm1->tm_sec);
    printf("%d %d %d %d:%d:%d\n", tm2->tm_year+1900, tm2->tm_mon+1, tm2->tm_mday, tm2->tm_hour, tm2->tm_min, tm2->tm_sec);

    return 0; 
}



잠들기

#include <unistd.h>

unsigned int sleep(unsigned int seconds); 
int usleep(useconds_t usec);


#include <time.h>

int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);


retry:
ret = nanosleep (&req, &rem); 
if (ret) {
    if (errno == EINTR) { 
        req.tv_sec = rem.tv_sec; 
        req.tv_nsec = rem.tv_nsec; 
        goto retry;
    }
    perror("nanosleep error: "); 
}