unix高级编程之文件流重定向

来源:互联网 发布:淘宝卖家售后服务流程 编辑:程序博客网 时间:2024/06/05 02:21
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
int main()
{
    int fd = open("hello", O_RDWR | O_CREAT, 0664);//fd=3
    char msg[] = "hello tarena";
    if(fd == -1)
    {
        perror("open");
        return -1;
    }
    int s_fd =  dup(STDOUT_FILENO);//s_fd=4
    dup2(fd, STDOUT_FILENO);//
    close(fd);
    write(STDOUT_FILENO, msg, strlen(msg));
    
    dup2(s_fd, STDOUT_FILENO);
    write(STDOUT_FILENO, msg, strlen(msg));
    close(s_fd);
    return 0;
}