본문 바로가기
Language/C언어

C052_dup 함수 사용하기

by OdOp 관리자 2024. 1. 10.
SMALL

dup는 파일 디스크립터를 복사하는 것을 의미합니다. 

 

dup

#include <unistd.h>

int	dup(int fd);

 

복제하고 싶은 fd를 인자로 넣으면 반환값으로 복제된 파일디스크립터가 나옵니다. 만약 복제의 실패 시에 -1을 리턴합니다. 

 

아래의 코드는 exist의 파일 디스크립터를 복사하여 사용하는 것입니다. 

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

int main(void)
{
    int     fd;
    int     copy;
    char    buffer[1000];
    int     ret;

    fd = open("./exist", O_RDONLY);
    if (fd < 0)
        return (0);
    copy = dup(fd);
    if (copy == -1)
    {
        close(fd);
        return (0);
    }
    close(fd);
    ret = read(copy, buffer, 1000);
    close(copy);
    if (ret < 0)
        return (0);
    buffer[ret] = '\0';
    printf("%s", buffer);
    return (0);
}

 

 

LIST

'Language > C언어' 카테고리의 다른 글

C054_open 함수 사용하기  (0) 2024.01.12
C053_dup2 함수 사용하기  (0) 2024.01.11
C051_waitpid 함수 사용하기  (1) 2024.01.09
C050_wait 함수 사용하기  (1) 2024.01.08
C049_fork 함수 사용하기  (2) 2024.01.07