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
Mode | Description |
---|---|
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
'Linux' 카테고리의 다른 글
[Linux System Programming] GCC 컴파일러 사용법 #2 (0) | 2022.09.26 |
---|---|
[Linux System Programming] vi cheat sheet #1 (0) | 2022.09.26 |
[Python] setup.py와 requirements.txt의 차이점과 사용방법 (0) | 2022.09.06 |
[Linux System Programming] Makefile 기초, 변수, 생성 규칙, 재귀, 함수... (0) | 2022.09.05 |