输出重定向
本质在OS内部,更改fd对应内容的指向
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
//myfile helloworld
//int main(int argc, char *argv[])
int main()
{
close(1);
// 这里的fd的分配规则是: 最小的,没有被占用的文件描述符
// 0,1,2 -> close(1) -> fd -> 1
int fd = open("log.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
if(fd < 0)
{
perror("open");
return 1;
}
// 都应该是往显示器(标准输出)打印的!
// 但是下面的都写入(显示)到了log.txt
// 这是什么呢?输出重定向
printf("fd: %d\n", fd); // stdout->FILE{fileno=1}->log.txt
printf("fd: %d\n", fd);
printf("fd: %d\n", fd);
printf("fd: %d\n", fd);
printf("fd: %d\n", fd);
printf("fd: %d\n", fd);
fprintf(stdout, "hello fprintf\n");
const char *s = "hello fwrite\n";
fwrite(s, strlen(s), 1, stdout);
不关心
fflush(stdout);
//stdout->_fileno == 1;
close(fd);
return 0;
}
从上往下找,匹配数字最小的
输入重定向
close(0);
int fd = open("log.txt", O_RONLY);
if(fd<0)
{
perror("open");
return 1;
}
printf("fd: %d\n", fd);
char buffer[64];
fgets(buffer, sizeof buffer, stdin);
printf("%s\n", buffer);
追加重定向
close(1);
int fd = open("log.txt", O_WRONLY | O_APPEND | O_CREAT);
if(fd<0)
{
perror("open");
return 1;
}
fprintf(stdout, "you can see me , success\n");
dup2(系统调用重定向)
如何理解一切皆文件?
一切都被描述为struct file
缓冲区
一块内存空间:存够一定数据就会刷新
刷新策略
1.立即刷新
2.行刷新(行缓冲)遇到\n
3.满刷新(全缓冲)
特殊情况
1.用户强制刷新(fflush)
2.进程退出
重定向后,fork导致次数增多(缓冲区刷新策略)