dup2函数示例

2020-07-22  本文已影响0人  一路向后

1.函数功能

int dup2(int oldfd, int targetfd);  关闭newfd并打开oldfd

2.程序源码

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

int main()
{
    char *buf1 = "hello";
    char *buf2 = " world\n";
    int fd1 = open("a.txt", O_RDWR|O_CREAT);
    int fd2 = open("b.txt", O_RDWR|O_CREAT);
    int ret = 0;

    if(fd1 < 0 || fd2 < 0)
    {
        perror("open");
        exit(-1);
    }

    printf("file open fd1=%d\n", fd1);
    printf("file open fd2=%d\n", fd2);

    ret = dup2(fd1, fd2);
    if(ret < 0)
    {
        perror("dup2");
        exit(-1);
    }

    printf("file dup fd1=%d\n", fd1);
    printf("file dup fd2=%d\n", fd2);

    write(fd1, buf1, strlen(buf1));
    write(fd2, buf2, strlen(buf2));

    return 0;
}

4.编译源码

$ gcc -o dup2 dup2.c

5.运行程序

$ ./dup
file open fd1=3
file open fd2=4
file dup fd1=3
file dup fd2=4

6.查看文件数据

$ cat a.txt
hello world
$ cat b.txt

上一篇下一篇

猜你喜欢

热点阅读