이 포스팅은 한국기술교육대학교 김덕수 교수님의 시스템 프로그래밍 (CSE 232)를 참고하여 작성되었습니다.
#1 Duplication FD - dup(2) / dup2(2)
#include <unistd.h>
int dup(int oldfd);
int dup2(int oldfd, int newfd);
oldfd (old file descriptor) : 복사하려는 file descriptor
newfd (old file descriptor) : 새로운 fd 지정, dup()의 경우 할당 가능한 fd 중 가장 작은 값 할당
Return : oldfd를 복사한 새로운 fd , -1 = error
IO redirection
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int fd, fd1;
fd = open("tmp.aaa", O_CREAT | O_WRONLY | O_TRUNC, 0644);
if (fd == -1)
{
perror("Create tmp.aaa");
exit(1);
}
close(1); // close stdout
fd1 = dup(fd); // duplicate fd, fd1 will get 1 ==> redirect standard output to the file
printf("DUP FD=%d\n", fd1);
printf("Standard output redirection\n");
close(fd);
return 0;
}
기존의 1번 파일 디스크립터인 표준 출력을 close(1)을 통해서 끊는다.
해당 파일의 표준 출력 연결이 끊겼기 때문에 printf 함수를 실행해도 터미널에 출력되지 않는다.
#2 Manipulating FD - fcntl(2)
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd, ... /* arg */ );
fd (file descriptor) : 대상 file descriptor
cmd (command) : 수행할 명령
ex ) F_GETFL (상태 flag 읽기), F_SETFL (상태 flag 설정) emd
arg (argument) : cmd에 필요한 인자들
Return : cmd에 따라 다름
Changing FD flag
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
int fd, flags;
fd = open("linux.txt", O_RDWR);
if (fd == -1) {
perror("open linux.txt");
exit(1);
}
if ((flags = fcntl(fd, F_GETFL)) == -1) {
perror("fcntl");
exit(1);
}
flags |= O_APPEND; // change to append mode
if (fcntl(fd, F_SETFL, flags) == -1) {
perror("fcntl");
exit(1);
}
if (write(fd, "KOREATECH", 9) != 9) perror("write");
close(fd);
return 0;
}
#3 Summary
File : 보조 기억 장치에 저장된 연관된 정보들의 집합
OS는 file을 다루기 위한 system call을 제공
- Low-level IO
File open/close
File read/write
- File offset 이동 (directed access)
- File synchronization
File descriptor 다루기
긴 글 읽어주셔서 감사드립니다.
22.12.13
'TIL (Today I Learned) > 컴퓨터 시스템(CS)' 카테고리의 다른 글
[CS] 표준 입출력, Standard IO #2 (0) | 2022.12.14 |
---|---|
[CS] 표준 입출력, Buffered IO #1 (0) | 2022.12.14 |
[CS] File, 파일 읽기/쓰기 #3 (0) | 2022.12.13 |
[CS] File, 파일 열기/닫기 #2 (1) | 2022.12.13 |
[CS] File, 파일이 무엇인가? #1 (0) | 2022.12.13 |
댓글