"creat" Unix 中的系统调用
"creat" System Call in Unix
我正在使用 creat 系统调用来创建文件。下面是创建文件的程序
#include<stdio.h>
#include<fcntl.h>
void main()
{
int fd=creat("a.txt",S_IRWXU|S_IWUSR|S_IRGRP|S_IROTH);
printf("fd = %d\n",fd);
}
所以,首先,程序会创建一个名为 a.txt 的文件,并具有适当的权限。如果我再执行一次 a.out,就会创建新的 a.txt。但是,文件的 inode 保持不变。怎么样,会怎样。
$ ./a.out
fd = 3
$ ls -li a.txt
2444 -rw-r--r-- 1 mohanraj mohanraj 0 Aug 27 15:02 a.txt
$ cat>a.txt
this is file a.txt
$ ./a.out
fd = 3
$ cat a.txt
$ls -li a.txt
2444 -rw-r--r-- 1 mohanraj mohanraj 0 Aug 27 15:02 a.txt
$
在上面的输出中,a.txt 的内容为 "This is file a.txt"。一旦我执行 a.out,就会创建新的 a.txt。但是,索引节点
2444 保持不变。那么,创建系统调用是如何工作的?
提前致谢。
creat
只创建不存在的文件。如果它已经存在,它只是被截断。
creat(filename, mode);
等同于
open(filename, O_WRONLY|O_CREAT|O_TRUNC, mode);
并且如 open(2)
文档中所述:
O_CREAT
If the file does not exist it will be created.
我正在使用 creat 系统调用来创建文件。下面是创建文件的程序
#include<stdio.h>
#include<fcntl.h>
void main()
{
int fd=creat("a.txt",S_IRWXU|S_IWUSR|S_IRGRP|S_IROTH);
printf("fd = %d\n",fd);
}
所以,首先,程序会创建一个名为 a.txt 的文件,并具有适当的权限。如果我再执行一次 a.out,就会创建新的 a.txt。但是,文件的 inode 保持不变。怎么样,会怎样。
$ ./a.out
fd = 3
$ ls -li a.txt
2444 -rw-r--r-- 1 mohanraj mohanraj 0 Aug 27 15:02 a.txt
$ cat>a.txt
this is file a.txt
$ ./a.out
fd = 3
$ cat a.txt
$ls -li a.txt
2444 -rw-r--r-- 1 mohanraj mohanraj 0 Aug 27 15:02 a.txt
$
在上面的输出中,a.txt 的内容为 "This is file a.txt"。一旦我执行 a.out,就会创建新的 a.txt。但是,索引节点 2444 保持不变。那么,创建系统调用是如何工作的?
提前致谢。
creat
只创建不存在的文件。如果它已经存在,它只是被截断。
creat(filename, mode);
等同于
open(filename, O_WRONLY|O_CREAT|O_TRUNC, mode);
并且如 open(2)
文档中所述:
O_CREAT
If the file does not exist it will be created.