美文网首页
dup函数示例

dup函数示例

作者: 一路向后 | 来源:发表于2020-07-22 22:00 被阅读0次

1.函数功能

int dup (int 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 fd = open("a.txt", O_RDWR|O_CREAT);
    int ret = 0;

    if(fd < 0)
    {
        perror("open");
        exit(-1);
    }

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

    ret = dup(fd);
    if(ret < 0)
    {
        perror("dup");
        exit(-1);
    }

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

    write(fd, buf1, strlen(buf1));
    write(ret, buf2, strlen(buf2));

    return 0;
}

4.编译源码

$ gcc -o dup dup.c

5.运行程序

$ ./dup
file open fd=3
file dup ret=4

6.查看文件数据

$ cat a.txt
hello world

相关文章

网友评论

      本文标题:dup函数示例

      本文链接:https://www.haomeiwen.com/subject/jtkxlktx.html