Linux 1.文件编程(dup、dup2)

发布于:2024-04-20 ⋅ 阅读:(30) ⋅ 点赞:(0)

重定向是什么?

进程在最开始运行的时候,首先打开了三个文件,分别是标准输入流、标准输出流、标准错误输出流。证明的时候我是把标准输出留给关闭了,然后紧接着创建的文件就会占用已关闭的标准输出流,使得本该流向显示器的数据流向了新创建的文件。先不谈底层的原理,就只看表象,就像是使数据流的方向从一个方向,指向了另一个方向,完成了数据流的方向重定向。现在再次理解重定向就好理解得多了:重新锚定方向
————————————————

                        版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

原文链接:https://blog.csdn.net/qq_63412763/article/details/127732577

dup

#include <unistd.h>

int dup(int fd);
int dup2(int fd1,int fd2);

两个均为复制一个现存的文件的描述。

两个函数的返回:若成功为新的文件描述,若出错为-1;

由dup返回的新文件描述符一定是当前可用文件描述中的最小数值。用dup2则可以用fd2参数指定新的描述符数值。如果fd2已经打开,则先关闭。若fd1=fd2,则dup2返回fd2,而不关闭它。通常使用这两个系统调用来重定向一个打开的文件描述符。

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>

/*
 * ./dup 1.txt
 * argc    = 2
 * argv[0] = "./dup"
 * argv[1] = "file"
 * ...
 */

int main(int argc, char **argv)
{
    char buf[10];
    char buf2[10];
    
    if (argc != 2)
    {
        printf("Usage: %s <file>\n", argv[0]);
        return -1;
    }

    int fd = open(argv[1], O_RDONLY);
    int fd2 = open(argv[1], O_RDONLY);
    int fd3 = dup(fd);

    printf("fd = %d\n", fd);
    printf("fd2 = %d\n", fd2);
    printf("fd3 = %d\n", fd3);

    if (fd < 0 || fd2 < 0 || fd3 < 0)
    {
        printf("can not open %s\n", argv[1]);
        return -1;
    }

    read(fd, buf, 1);
    read(fd2, buf2, 1);

    printf("data get from fd : %c\n", buf[0]);
    printf("data get from fd2: %c\n", buf2[0]);
    
    read(fd3, buf, 1);
    printf("data get from fd3: %c\n", buf[0]);
    
    return 0;
}

在这里插入图片描述

dup2

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

/*
 * ./dup2 1.txt
 * argc    = 2
 * argv[0] = "./dup2"
 * argv[1] = "file"
 * ...
*/

int main(int argc,char **argv)
{
	int fd = 0;

	if(argc < 2)
	{
		printf("Usage:%s <file>\n",argv[0]);

		return -1;
	}

	fd = open(argv[1],O_RDWR | O_CREAT | O_TRUNC,0666);
	
	if(fd < 0)
	{
		printf("Can not open %s!\n",argv[1]);
		printf("errno = %d\n",errno);
		printf("%s\n",strerror(errno));

		return -1;
	}

	else
	{
		printf("fd = %d\n",fd);
		
	}

	dup2(fd,1);

	printf("hello,world\n");

	return 0;
}

在这里插入图片描述