[Linux system programming] 19.dup, dup2

Table of contents

dup

parameter oldfd

return value

test code 1

Test Results

dup2

parameter oldfd

parameter newfd

return value

Test code 2

Test Results

Test code 3

Test Results

File redirection.

 

dup

        File descriptor copy. Use the existing file descriptor to copy and generate a new file descriptor, and the two file descriptors before and after the function call point to the same file. Save it for later use.

man 2 dup

 

parameter oldfd

There is already a file descriptor.

return value

new file descriptor.

test code 1

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

int main(int argc, char *argv[])
{
    int fd = open(argv[1], O_RDWR);		//得到一个文件描述符
    int fd1 = dup(fd);		//文件描述符拷贝
    printf("fd=%d\n", fd);
    printf("fd1=%d\n", fd1);
    close(fd);
    close(fd1);
    return 0;
}

Test Results

dup2

        File descriptor copy. The redirected file descriptor points to. Through this function, the command line "redirection" function can be realized. Make the file descriptor originally pointing to a file point to other specified files.

man 2 dup2

parameter oldfd

An existing file descriptor.

parameter newfd

The file descriptor to be redirected.

return value

Success: newfd

Failed: -1

Test code 2

        Read two files, modify the redirection of the second file descriptor to the first file descriptor, then write content to the second file descriptor, modify the file descriptor of 1 and redirect it to the first file, Terminal output content.

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

int main(int argc, char *argv[])
{
    int fd1 = open(argv[1], O_RDWR);
    int fd2 = open(argv[2], O_RDWR);
    int flag;
    flag= dup2(fd1, fd2);		//fd2文件描述符重定向到fd1文件描述符
    flag=write(fd2,"hello world!",12);
    if(flag<0){
        perror("write error");
    }
    dup2(fd1,STDOUT_FILENO);		//终端输出重定向到fd1
    printf("\n你好,世界!\n");
    close(fd1);
    close(fd2);
    return 0;
}

Test Results

Test code 3

The function of dup is realized by fcntl.

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

int main(int argc, char *argv[])
{
    int fd1 = open(argv[1], O_RDWR);
    printf("fd1:%d\n", fd1);
    int fd2=fcntl(fd1,F_DUPFD,0);	//已被占用的文件描述符,返回最小可用的
    printf("fd2:%d\n",fd2);
    int fd3=fcntl(fd1,F_DUPFD,7);	//未被占用的文件描述符,返回该值
    printf("fd3:%d\n",fd3);
    close(fd1);
    close(fd2);
    close(fd3);
    return 0;
}

Test Results

Guess you like

Origin blog.csdn.net/CETET/article/details/131026114