본문 바로가기

not기초/시스템프로그래밍

[시스템프로그래밍]시스템 호출 open()/creat()/close()

open()

  1. path가 나타내는 파일을 oflag 모드로 연다
  2. prototype
  3. #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h> // 파일을 새로 만들때의 권한
    int open (const char *path, ing oflag, [mode_t mode];

    성공 시 파일 디스크립터를, 실패 시 -1을 리턴한다

  4. oflag : 대상의 입출력 방식을 지정함
    • O_RDONLY : 읽기 모드, read() 호출 가능
    • O_WRONLY : 쓰기 모드, write() 호출 가능
    • O_RDWR : 읽기/쓰기 모드, read()/write() 호출 가능
      (여기까지 필수 지정/다음부터 선택 지정)
    • O_APPEND : 파일 끝에 데이터 첨부
    • O_CREAT : 해당 파일이 없는 경우 파일 생성
      mode는 생성할 파일의 사용권한을 나타낸다
    • O_TRUNC : 해당 파일이 있는 경우 내용 삭제
    • O_EXCL : O_CREAT와 함께 사용되며 해당 파일이 이미 있으면 에러 발생
    • O_NONBLOCK : 넌블로킹모드로 입출력 하도록 함
    • O_SYNC : write() 시스템 호출을 하면 디스크에 물리적으로 쓴 후 반환
  5. 파일 열기 예시
    • fd = open("account", O_RDONLY);
    • fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0600);
    • fd = open("/sys/log", O_WRONLY | O_APPEND | O_CREAT, 0600);
  6. fopen.c
  7. #include <stdio.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    
    int main(int argc, char *argv[]) {
    	int fd;
    	if ((fd = open(argv[1], O_RDWR)) == -1)
    		perror(argv[1]);
    	printf("파일 %s 열기 성공\n", argv[1]);
    	close(fd);
    	exit(0);
    }

creat()

  1. path가 나타내는 파일을 생성하고 쓰기 전용으로 열며, 생성된 파일의 사용권한은 mode로 정한다
  2. 기존 파일이 있을 경우에는 그 내용을 삭제하고 연다
  3. open(path, WRONLY | O_CREAT | O_TRUNC, mode);와 동일하다
  4. prototype
  5. #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    int creat(const char *path, mode_t mode);

    성공 시 파일 디스크립터를, 실패 시 -1을 리턴한다

close()

  1. fd가 나타내는 파일을 닫는다
  2. prototype
  3. #include <unistd.h>
    int close(int fd);

    성공 시 파일 디스크립터를, 실패 시 -1을 리턴한다