C & LINUX

C / LINUX dup() dup2()

Ocean_ 2022. 5. 1. 18:23

함수 기능

기존 파일 디스크립터를 복사하기 위한 시스템 호출

함수 원형

#include<unistd.h>
Int dup(int filedes)
Int dup2(int filedes, int filedes2)

리턴 값 : 성공시 새로운 파일 디스크립터, dup2는 filedes2리턴 에러시 -1

함수 파라메터

filedes

파일 디스크립터

filedes2

두번째 파일 디스크립터

함수 예제

dup1

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

#define BUFFER_SIZE 1024

int main(void){
    char buf[BUFFER_SIZE];
    char *fname = "ssu_test.txt";
    int count;
    int fd1, fd2;

    if((fd1 = open(fname,O_RDONLY,0644))<0){
        fprintf(stderr,"open error for %s\n", fname);
        exit(1);
    }

    fd2 = dup(fd1);
    count = read(fd1, buf, 12);
    buf[count] = 0;
    printf("fd1's printf : %s\n",buf);
    lseek(fd1, 1, SEEK_CUR);
    count = read(fd2, buf, 12);
    buf[count]=0;
    printf("fd2's printf : %s\n",buf);
    exit(0);
}

dup2_1

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

int main(void){
    char *fname = "ssu_test.txt";
    int fd;

    if((fd=creat(fname,0666))<0){
        printf("creat error for %s\n",fname);
        exit(1);
    }

    printf("First printf is on the screen.\n");
    dup2(fd,1);
    printf("Second printf is in this file.\n");
    exit(0);
}

dup2_2

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

#define BUFFER_SIZE 1024

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

    if((fd=open(fname,O_RDONLY,0644))<0){
        fprintf(stderr, "open error for %s\n",fname);
        exit(1);
    }

    if(dup2(1,4)!=4){
        fprintf(stderr, "dup2 call failed\n");
        exit(1);
    }

    while(1){
        length = read(fd,buf,BUFFER_SIZE);

        if(length <=0)
            break;

        write(4, buf, length);
    }
    exit(0);
}

 

함수 결과

dup1

dup2_1

dup2_2

리눅스시스템 프로그래밍 - 홍지만 저

교재 내에 있는 예제를 바탕으로 작성한 글 입니다.