본문 바로가기

프로그래밍/C

[function] dup 함수 알아보기

📌 매뉴얼 (Linux)

더보기

NAME
       dup - duplicate a file descriptor
: 파일 디스크립터를 복제


SYNOPSIS
       #include <unistd.h>
       int dup(int oldfd);

DESCRIPTION
       The  dup()  system call creates a copy of the file descriptor oldfd, using the lowest-numbered
       unused file descriptor for the new descriptor.

       After a successful return, the old and new file descriptors may be used interchangeably.  They
       refer to the same open file description (see open(2)) and thus share file offset and file sta‐
       tus flags; for example, if the file offset is modified by using lseek(2) on one  of  the  file
       descriptors, the offset is also changed for the other.

       The  two  file  descriptors  do not share file descriptor flags (the close-on-exec flag).  The
       close-on-exec flag (FD_CLOEXEC; see fcntl(2)) for the duplicate descriptor is off.

: dup() 시스템 호출은 새 디스크립터에 대해 가장 낮은 번호의 미사용 파일 디스크립터를 사용하여

파일 디스크립터 oldfd의 복사본을 만듭니다.

성공적으로 반환된 후에는 이전 파일 디스크립터와 새 파일 디스크립터를 상호 교환하여 사용할 수 있습니다.

파일 디스크립터는 동일한 열린 파일 디스크립터(open(2))를 참조하므로 파일 오프셋과 파일 상태 플래그를

공유합니다. 예를 들어, 파일 디스크립터 중 하나에서 lseek(2)를 사용하여 파일 오프셋을 수정하면

다른 파일 디스크립터에서도 오프셋이 변경됩니다.

두 파일 디스크립터는 파일 디스크립터 플래그(close-on-exec 플래그)를 공유하지 않습니다.

중복 디스크립터에 대한 close-on-exec 플래그(FD_CLOEXEC; fcntl(2) 참조)는 off입니다.


RETURN VALUE
       On  success, these system calls return the new file descriptor.  On error, -1 is returned, and
       errno is set appropriately.

: 성공 시 이러한 시스템 호출은 새 파일 디스크립터를 반환합니다.

오류 시 -1이 반환되고 errno가 적절하게 설정됩니다.

📌 함수 설명

dup 함수는 fd로 전달받은 파일 서술자를 복제하여 반환한다. 현재 사용하고 있지 않은 fd 중 가장 낮은 fd를 반환하며,

해당 fd는 전달받은 파일 서술자가 가리키는 파일 (또는 표준입출력)을 동일하게 가리킨다.

 

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

int main()
{
	int fd1, fd2;
	fd1 = open("a.txt",O_RDWR);
	fd2 = dup(fd1);
	write(fd2, "abc", 3);
	printf("fd1 : %d, fd2 : %d", fd1, fd2);
	close(fd1);
	close(fd2);
	return (0);
}

 

이 프로그램은 a.txt의 파일을 열어 해당 파일 디스크립터를 fd1에 저장하고,

dup을 이용해 fd1의 파일 디스크립터가 가리키는 파일을 fd2도 가리키게 하며, fd2를 fd1의 다음 숫자로 부여한다.

 

결과 - std_output)

fd1 : 3, fd2 : 4

 

결과 - a.txt)

abc

 

 

그림으로 설명을 덧붙이자면, 첫번째 그림에서 fd1은 표준입출력 및 에러 이후 가장 작은 fd인 3으로 배치되고,

open을 통해 a.txt의 파일 디스크립터가 된다. 그리고, 우리는 dup을 통해 fd2를 생성해주는데, 이는 3 이후 가장 작은

파일 디스크립터 숫자인 4가 부여되며, fd1이 복제되었기에, fd1이 가리키던 a.txt를 함께 가리키게 된다.

 

그리하여, fd2에 write를 하게되면, a.txt에 작성이 된다.

Recent Posts
Popular Posts
Recent Comments