3.12 dup 会共享文件属性
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <sys/times.h>
#include <unistd.h>
#include <sys/param.h>
#include <fcntl.h>
#include <string.h>
extern int errno;
void err_sys(const char *msg) {
perror(msg);
exit(errno);
}
int
main (int argc, char **argv)
{
int fd = open("A.txt",
O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH);
if (fd == -1) {
err_sys("open");
}
int fd2 = dup(fd);
if (fd2 == -1) {
err_sys("dup");
}
const char *msg;
size_t n;
msg = "first message";
n = strlen(msg);
if (write(fd, msg, n) != n) {
err_sys("write fd");
}
msg = "second message";
n = strlen(msg);
if (write(fd2, msg, n) != n) {
err_sys("write fd2");
}
}
结果:两条消息按顺序写入了文件,后者并没有覆盖前者。