0xSEUNGJU
CodeMonkie
0xSEUNGJU
전체 방문자
오늘
어제
  • 분류 전체보기 (15)
    • linux (8)
    • web (2)
    • android (0)
    • data science (1)
    • algorithms (3)
    • 보안 (1)
    • hardware (0)

블로그 메뉴

  • github
  • playground

공지사항

인기 글

태그

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
0xSEUNGJU

CodeMonkie

Linux File System
linux

Linux File System

2022. 9. 27. 11:11

Linux File Structure

리눅스는 모든 게 다 파일로 이루어져있다. 파일 시스템을 이해하는 것은 파일 입출력 작업을 수행하고 리눅스/유닉스 시스템을 이해하는 데 시작점이라고 할 수 있다.

System Call

  • open
  • read
  • write
  • close
  • ioctl (device driver에 제어 정보 전달)

 

Low-Level File Access

리눅스에선 기본적으로 3가지의 파일이 열려있고 각 파일을 id로 구분한다. 다음 3 파일은 운영체제가 시작되면서 바로 오픈된다.

  • 0: standard input(stdin)
  • 1: standard output(stdout)
  • 2: standard error(stderr)

 

write

사용법

man 2 write
  • 1번 매뉴얼: 리눅스 명령어관련
  • 2번 매뉴얼: 시스템 콜
  • 3번 매뉴얼: c언어

예시

// write.c
#include <unistd.h> // write()
#include <stdlib.h> // exit()

int main() {
    if((write(1, "Here is some data\n", 18)) != 18) // stdout이 8글자가 아니면 
        write(2, "file descriptor에 쓰기 에러가 발생\n", 46) // stderr로 에러 메세지 출력
    exit(0);
}
gcc -o write write.c
./write

 

read

사용법

#include <unistd.h>
size_t read(int fd, void *buf, size_t count);

예시

#include <unistd.h>
#include <stdlib.h>

int main() {
    char buffer[128];
    int nread;

    nread = read(0, buffer, 128); // stdin으로 입력을 받아서 buffer에 128자까지 쓰고 size를 nread에 담음
    if(nread == -1) {
        write(2, "A read error has occurred\n", 26);

    if(write(1, buffer, nread) != nread)
        write(2, "A write error has occured\n", 27);

    exit(0);
}

 

open

사용법

#include <fcntl.h>
#incldue <sys/types.h>
#include <sys/stat.h>

int open(const char *path, int oflags);
int open(const char *path, int oflags, mode_t mode);

Flag

ModeDescription

O_RDONLY Open for Read-Only
O_WRONLY Open for Write-Only
O_RDWR Open for Reading and Writing

Mode

  • 파일 소유자의 읽기/쓰기/실행 권한, 소유자 그룹의 읽기/쓰기/실행 권한, Other의 읽기/쓰기/실행 권한
  • 예를 들어 0755면 사용자는 읽기/쓰기/실행, 소유자 그룹과 Other는 읽기/실행권한을 가짐

 

close

사용법

#include <unistd.h>
int close(int fd);
int ioctl(int fd, int cmd, ...);

 

Example

cp 명령어

// ex_cp.c
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main() {
    char c;
    int in, out;

    in = open("file.in", O_RDONLY); // read only로 file.in을 열고
    out = open("file.out", O_WRONLY|O_CREAT, 0755); // write only 또는 생성모드로 file.out을 열고
    while(read(in, &c, 1) == 1) // 한글자 씩 읽는데 size가 1일 때까지
        write(out, &c, 1); // out파일에 1글자 씩 쓰기

    exit(0);
}

 

References

  • [리눅스 시스템 프로그래밍] 2. 파일 시스템(File System)
  • 리눅스 시스템 프로그래밍 - Working with Files

'linux' 카테고리의 다른 글

리눅스 커널 구조  (0) 2022.10.05
운영체제 동작 사례  (0) 2022.10.04
Makefile tutorial  (0) 2022.09.28
GCC 컴파일러 사용법  (1) 2022.09.27
vi cheat sheet  (0) 2022.09.27
    'linux' 카테고리의 다른 글
    • 운영체제 동작 사례
    • Makefile tutorial
    • GCC 컴파일러 사용법
    • vi cheat sheet
    0xSEUNGJU
    0xSEUNGJU

    티스토리툴바