apue读书笔记【九】:复制一个现存的文件描述符 dup dup2 fcntl

复制一个现存的文件的描述

函数名称:dup dup2

函数原型:

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

函数功能:复制一个现存的文件的描述

返回值:若成功为新的文件描述,若出错为-1;

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

          demo:把hello打印到test2.txt中
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>


#define ERR_EXIT(m) \
	do \
	{ \
		perror(m); \
		exit(EXIT_FAILURE); \
	} while(0)

int main(int argc, char *argv[])
{
	int fd;
	fd = open("test2.txt", O_WRONLY);
	if (fd == -1)
		ERR_EXIT("open error");

/*
	close(1);
	dup(fd);
*/
	dup2(fd, 1);
	printf("hello\n");
	return 0;
}



函数名称:fcntl

函数原型:int fcntl(int fd, int cmd, long arg);

函数功能:复制一个现存的文件的描述

返回值:若成功为新的文件描述,若出错为-1;


#include <sys/types.h>   /*for open*/
#include <sys/stat.h>    /*for open*/
#include <fcntl.h>       /*for open fcntl*/
#include <stdlib.h>       /*for  perror exit*/
#include <stdio.h>        /*for  perror*/


#define ERR_EXIT(m) \
    do \
    { \
        perror(m); \
        exit(EXIT_FAILURE); \
    } while(0)


int main(int argc, char *argv[])
{
    int fd;
    fd = open("test.txt", O_WRONLY);
    if (fd == -1)
        ERR_EXIT("open error");

    close(1);
    if (fcntl(fd, F_DUPFD, 0) < 0)
        ERR_EXIT("dup fd error");
    printf("-----------\n");//进行重定向,将不会显示在标准输出,
    return 0;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值