#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
void my_err(const char *err_string, int line)
{
fprintf(stderr, "line:%d", line);
perror(err_string);
exit(1);
}
int main()
{
int ret;
int access_mode;
int fd;
if ((fd = open("example_64", O_CREAT | O_TRUNC | O_RDWR, S_IRWXU)) == -1)
my_err("open", __LINE__);
/* 設定檔案狀態標誌 */
if ((ret = fcntl(fd, F_SETFL, O_APPEND)) < 0)
my_err("fcntl", __LINE__);
/* 取得檔案狀態標誌 */
if ((ret = fcntl(fd, F_GETFL, 0)) < 0)
my_err("fcntl", __LINE__);
access_mode = ret & O_ACCMODE;
if (access_mode == O_RDONLY)
printf("example_64 access mode: read only");
else if (access_mode == O_WRONLY)
printf("example_64 access mode: write only");
if (ret & O_APPEND)
printf(",append");
if (ret & O_SYNC)
printf(",sync");
printf("\n");
return 0;
}
open 這行以讀寫方式開啟 example_64,不存在則建立、存在則清空,權限設為擁有者可讀寫執行;失敗時呼叫自訂的錯誤處理函式。
man fcntl 的原文是:Set the file status flags to the value specified by arg,也就是把參數 arg 指定的狀態標誌設上去。
但文件也明確指出,在 Linux 下這個命令只能改動 O_APPEND、O_ASYNC、O_DIRECT、O_NOATIME、O_NONBLOCK 這幾個標誌;檔案存取模式(O_RDONLY、O_WRONLY、O_RDWR)與建立相關標誌(O_CREAT、O_EXCL、O_NOCTTY、O_TRUNC)都會被忽略,而 O_DSYNC 與 O_SYNC 也無法透過它變更。
取得檔案存取模式與狀態標誌,arg 被忽略,回傳值即為狀態標誌。
O_ACCMODE 的值是 3(二進位 11),因此 ret & O_ACCMODE 等於取出 ret 的低位元,用來判斷檔案究竟是以唯讀、唯寫還是讀寫方式開啟。
複製檔案描述符有兩種方式:dup(fd) 會回傳當前最小未使用的描述符;dup2(oldfd, newfd) 則明確指定目標描述符,若 newfd 已被占用會先關閉它,並回傳 newfd。兩者複製出的描述符共用同一份檔案狀態標誌與位移量,這也是 shell 中 2>&1 重導向的底層原理。