#include <sys/time.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>

int main(void){

        struct timeval first_time;
        struct timeval second_time;

        if(gettimeofday(&first_time, NULL) != 0){
                perror("error occured");
                return -1;
        }

        for(int i=0; i<5; i++){
                //fprintf(stderr, "%d ", i);
                printf("%d \n", i);
                sleep(1);
        }
        printf("\n");

        if(gettimeofday(&second_time, NULL) != 0){
                perror("error occured");
                return -1;
        }

        time_t diff_time = (second_time.tv_sec - first_time.tv_sec) + (second_time.tv_usec - first_time.tv_usec)*pow(10, -9);
        printf("diff time is %ld \n", diff_time);
        return 0;


}

 

일정 시간동안 실행을 멈추고 싶다면 sleep 함수를 사용하면 된다  (sleep함수는 <unistd.h> 파일 내에 선언되어 있다)

인자로는 멈추고 싶은 sec를 정수로 입력해주면 된다.

 

  • calling thread는 signal이 전달되거나 명시한 초가 지날때까지 실행을 정지한다.
  • 만약 명시된 시간(초)이 다 지난 경우 0을 리턴하고
  • EINRT가 발생한 경우에는 남은 시간을 리턴한다. 

 

 

  • 표준출력장치에 printf를 통해 출력하게 되면 -> line buffered라는 것을 기억하자.
    • 만약 위의 코드에서 printf("%d ", i) 이렇게 하면 line buffered이기 때문에 전체 실행이 종료된 후 출력된다.
  • 따라서 printf("%d ", i) 이렇게 출력하고 싶다면 fprintf(stderr, "%d ", i)를 통해 buffer를 거치지 않고 바로 출력되도록 해야한다.

 

 

'다전공_컴퓨터공학 > 시스템프로그래밍, 운영체제' 카테고리의 다른 글

[SP] atomic  (0) 2020.12.03
[SP] unlink, remove  (0) 2020.12.03
[SP] async-signal safe  (0) 2020.12.01
[SP] write(2) return 0의 의미  (0) 2020.10.14
[SP] C 컴파일, 링크  (0) 2020.10.14

+ Recent posts