C,C++ & Linux

C/C++ dup2()

KyooDong 2020. 5. 16. 23:22
728x90

dup2(2) 함수 기능

파일 디스크립터를 지정된 파일 디스크립터 번호로 복사합니다.

함수 원형

#include <unistd.h>

int dup2(int fd, int destFd);

매개변수

fd

복사할 파일 디스크립터

 

destFd

복사된 파일 디스크립터 번호

반환값

성공 시 destFd 리턴

에러 시 -1 리턴하고 errno 설정

예제

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

#define BUFFER_SIZE 1024

int main(int argc, char *argv[]) {
    char *fname = "ssu_test.txt";
    int fd;

    // ssu_test.txt 파일 생성
    fd = creat(fname, 0666);
    printf("First printf is on the screen.\n");

    // ssu_test.txt 파일 디스크립터를 1번(표준 출력)으로 복사
    dup2(fd, 1);

    // 여기서부터는 표준 출력이 ssu_test.txt 로 바뀌어버림
    printf("Second printf is in this file.\n");

	exit(0);
}

결과

예제2

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

#define BUFFER_SIZE 1024

int main(int argc, char *argv[]) {
    char buf[BUFFER_SIZE];
    char *fname = "ssu_test.txt";
    int fd;
    int length;

    // 3번 = ssu_test.txt
    fd = open(fname, O_RDONLY, 0644);

    // 4번 = 1번(표준 출력)의 복사본
    if (dup2(1, 4) != 4) {
        fprintf(stderr, "dup2 call failed\n");
        exit(1);
    }

    while (1) {
        // ssu_test.txt 를 읽어서
        length = read(fd, buf, BUFFER_SIZE);

        if (length <= 0)
            break;
        
        // 표준 출력에 쓰기
        write(4, buf, length);
    }

	exit(0);
}

결과

 

 

 

 

 

 

 

 

 

리눅스시스템프로그래밍 저자 : 홍지만
https://book.naver.com/bookdb/book_detail.nhn?bid=14623672

책에 기술된 예제 프로그램입니다. 책 내부에는 훨씬 더 많은 자료가 있습니다. (개인적으로 좋았습니다.)