C 언어에서 이미 열린 파일의 플래그를 읽거나 바꾸고, 파일 잠금을 설정할 때 fcntl()을 쓴다.
작게 실행해 보기
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/uio.h>
int main(void) {
FILE *fp = tmpfile();
if (!fp)
return 1;
if (fputs("abcdef", fp) == EOF || fflush(fp) == EOF) {
fclose(fp);
return 1;
}
int fd = fileno(fp);
if (fd < 0) {
fclose(fp);
return 1;
}
int flags = fcntl(fd, F_GETFL);
if (flags < 0) {
fclose(fp);
return 1;
}
printf("flags=%d\n", flags);
if (fclose(fp) == EOF)
return 1;
return 0;
}F_GETFL은 상태 플래그를 읽는 명령이라 성공 반환값이 단순 0이 아니라 플래그 비트다.
반환값과 주의점
성공 값은 cmd에 따라 달라진다. F_GETFL은 플래그를, F_DUPFD는 새 디스크립터를 반환하고 오류는 -1이다.
세 번째 인수는 cmd에 따라 정수이거나 구조체 포인터다. F_GETFL로 읽은 값에 O_NONBLOCK을 더한 뒤 F_SETFL로 쓰면 기존 플래그를 보존할 수 있다.
예제 실행 방법
gcc -std=c11 -Wall -Wextra example.c -lm -o example
./example
답글 달기