#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#define FNAME "tmp2"
int main(int argc, char *argv[]) {
int fd;
/* redirect hello to a file */
close(1); // close std output
fd = open(FNAME, O_WRONLY|O_CREAT|O_TRUNC, 0600);
if (fd < 0) {
perror("open()");
exit(1);
}
//close(1); // 关闭 1
//dup(fd); // dup会把fd复制一份,放在最大的位置,1被关了,fd就被复制到1
dup2(fd, 1); //把fd复制一份,放在1,这比上方的操作保证了原子性,不至于在close(1)之后,1被别人抢走,这样的话,fd被dup在哪就不一定了
if (fd != 1) {
close(1);
}
//最后要把1还原给标准输出!!!!!!!!!!!!!!
/* print hello on screen */
puts("hello!");
exit(0);
}
重定向输出 把hello输出到文件
最新推荐文章于 2023-06-05 20:50:55 发布