qfedu-linux-advanced-level/day4/file3_dup2.c

20 lines
594 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd = open("a.txt", O_WRONLY | O_CREAT | O_APPEND, 0644);
printf("新打开的hello fd\n"); // fd 描述符会变为 1 ,printf 回答引导 fd 对应文件中
// dup2 会自动关闭 newfd即关闭 1 标准输出
int newfd = dup2(fd, 1); // 1->a.txt, 会将新的 fd 描述符值为 1
close(fd);
// 下面的打印(写入)会重定向到 a.txt 文件中
printf("newfd = %d\n", newfd);
printf("no\n");
printf("good\n");
return 0;
}