dup/dup2输出重定向

有时我们希望把标准输入重定向到一个文件,或者把标准输出重定向到一个网络连接。

dup()与dup2()能对输入文件描述符进行重定向。

int dup(int oldfd);

int dup2(int oldfd, intnewfd);

dup函数创建一个新的文件描述符,该新文件描述符和原有文件描述符oldfd指向相同的文件、管道或者网络连接。

并且dup返回的文件描述符总是取系统当前可用的最小整数值。dup2和dup类似,不过它将返回第一个不小于oldfd的整数值。dup和dup2失败时返回-1并设置errno。

1.打开一个新文件

2.关掉标准输出文件符

3.调用dup给文件描述符

4.此时文件描述符变为1

5.将所要打印数据重定向到文件中


dup函数:

/*************************************************************************
	> File Name: dup.c
	> Author: fucang_zxx
	> Mail: fucang_zxx@163.com 
	> Created Time: Thu 28 Jul 2016 04:15:35 PM CST
 ************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>

int main()
{
	//打开一个文件
	int fd = open("./log", O_CREAT | O_RDWR, 0644);
	if(fd < 0)
	{
		perror("open");
		return 1;
	}
	//关闭标准输出文件描述符
	close(1);

	//进行重定向
	int new_fd = dup(fd); //new_fd = 1
	if(new_fd < 0)
	{
		perror("dup");
		return 2;
	}
	close(fd);

	char buf[1024];
	while(1)
	{
		memset(buf, '\0', sizeof(buf));
		ssize_t _s = read(0, buf, sizeof(buf) - 1);
		if(_s <  0)
		{
			perror("read");
			return 3;
		}
		else
		{
			buf[_s] = '\0';
		}
		if(strncmp("quit", buf, 4) == 0)
		{
			//退出
			break;
		}
		printf("%s", buf); //将往文件中写入
		fflush(stdout); //必须做,因为重定向后printf函数将由行缓冲变为全缓冲
		sleep(1);
	}
	close(new_fd);
	return 0;
}




dup2函数:

/*************************************************************************
	> File Name: dup2.c
	> Author: fucang_zxx
	> Mail: fucang_zxx@163.com 
	> Created Time: Thu 28 Jul 2016 04:56:35 PM CST
 ************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>

int main()
{
	//打开一个文件
	int fd = open("./log", O_CREAT | O_RDWR, 0644);
	if(fd < 0)
	{
		perror("open");
		return 1;
	}
	//关闭标准输出文件描述符
  //  close(1);  //dup2不需要手动关闭,系统会自动关闭

	//进行重定向
	int new_fd = dup2(fd, 1); //new_fd = 1
	if(new_fd < 0)
	{
		perror("dup2");
		return 2;
	}
	close(fd);

	char buf[1024];
	while(1)
	{
		memset(buf, '\0', sizeof(buf));
		ssize_t _s = read(0, buf, sizeof(buf) - 1);
		if(_s <  0)
		{
			perror("read");
			return 3;
		}
		else
		{
			buf[_s] = '\0';
		}
		if(strncmp("quit", buf, 4) == 0)
		{
			//退出
			break;
		}
		printf("%s", buf); //将往文件中写入
		fflush(stdout); //必须做,因为重定向后printf函数将由行缓冲变为全缓冲
		sleep(1);
	}
	close(new_fd);
	return 0;
}




  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值