상세 컨텐츠

본문 제목

UNIX system call - open

Computer Science/UNIX

by 2021. 9. 14. 18:38

본문

반응형

open(2)

#include <fcntl.h> 

int open(const char *pathname, int flags, [mode_t mode]);


// Returns: file descriptor if OK, -1 on error

open 은 fcntl.h에 있는 system call이며, 매개변수로 경로명, flags, mode(선택)이 들어간다.

flags의 종류는 다음과 같다.

  • O_RDONLY  #0  Open for reading only. 읽기 전용
  • O_WRONLY  #1  Open for writing only. 쓰기 전용
  • O_RDWR  #2  Open for reading and writing. 읽기 쓰기 가능

반드시 이중 하나의 상태를 설정해야하며, flags가 세 가지가 있는 이유는 O_RDONLY가 0이기 때문에 bitwise 연산으로

O_RDONLY | O_WRONLY == O_RDWR

의 연산이 불가능하기 때문이다. 

 

이외에도 다음과 같은 flags가 있고 이는 위 세 개의 flags와 함께 쓰인다.

O_APPEND    Append to the end of file on each write. 쓸 때 파일의 끝에 추가
O_CREAT    Create the file if it doesn't exist. 파일이 없을 때 생성
O_EXCL    Generate an error if O_CREAT is also specified and the file already exists. O_CREAT가 지정되었는데 파일이 존재할 경우 에러메시지 생성
O_TRUNC    If the file exists, truncate its length to 0. 파일이 존재하면 비우기
O_NONBLOCK    non-blocking file open. 

 

 flags 사용 예를 알아보자

fd = open(“/tmp/newfile”, O_WRONLY);
/* if isExist(file) “file open” else “file open error” */ 
// 파일이 있으면 반환값을 보내고, 없을 경우 error (-1 반환)

fd = open(“/tmp/newfile”, O_WRONLY|O_CREAT, 0644); // 0644는 permission
/* if isExist(file) “file open” else “file create & open” */ 
// 파일이 없을 경우 새로 생성해서 엶 (파일 생성시 permission이 필요)

fd = open(“/tmp/newfile”, O_WRONLY|O_CREAT|O_EXCL, 0644);
/* if isExist(file) “open error” else “file create & open” */
// 파일이 있으면 에러 반환, 없을 경우에만 생성 및 open (O_EXCL는 exclusive 배타적 효과)

fd = open(“/tmp/newfile”, O_WRONLY|O_CREAT|O_TRUNC, 0644);
/* if isExist(file) “file truncate & open ” else “file create & open” */
// 파일이 있을 경우 모두 비우고 open, 없을 경우 생성 및 open

fd = open(“/tmp/newfile”, O_WRONLY|O_APPEND, 0644);
/* if isExist(file) “file open and append to end” else “file open error” */
// 파일이 있을 경우 기존 데이터 뒤에 추가, 없을 경우 error

 

#include <stdlib.h>	/* exit() */
#include <fcntl.h>	/* open() */

char *workfile = “junk”;

main()
{
    int fd;
    if( (fd = open(workfile, O_RDWR)) == -1) // 상대경로를 R/W로 open
    {
        printf(“Couldn’t open %s\n”, workfile);
        exit(1);
    }

    exit(0);
    // 실행 종료 system call
}

 junk라는 이름의 파일이 담긴 포인터 주소를 경로로 open system call를 사용하였을 때, 파일이 없을 경우 error 값인 -1이 반환되므로 파일이 있는 경우 printf문을 통해 출력한다.

 

 

반응형

'Computer Science > UNIX' 카테고리의 다른 글

UNIX system call - create  (0) 2021.09.16
UNIX - File permissions 파일 권한  (0) 2021.09.15
UNIX의 파일체계  (0) 2021.09.13
UNIX의 구조와 기본적인 개념들  (0) 2021.09.05
Virtual Box 설치하기  (0) 2021.09.04

관련글 더보기