Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
05-20 19:12
관리 메뉴

zyint's blog

[4] dup2 본문

예전글들

[4] dup2

진트­ 2008. 4. 17. 23:26

 

dup2


        

기능

파일핸들(oldhandle)을 존재하는 파일핸들(newhandle)로 복사한다.

문법

#include<io.h>
int dup2(int oldhandle, int newhandle);

DOS

UNIX

Windows

ANSI C

C++ only

 

 

주석

dup2는 유닉스 시스템 III하에서는 실행되지 않는다.

dup2는 원래의 파일핸들과 같은 내용 새로운 파일핸들을 생성한다.

  ■ 동일한 파일 열기나 장치
  ■ 동일한 파일 포인터
  ■ 동일한 액세스 모드(읽기, 쓰기,읽기/쓰기)

dup2는 newhandle값의 새로운 파일핸들을 생성한다.  dup2가 호출되었을 때 newhandle과 연관된 파일이 열려있으면 파일은 닫혀진다.  newhandle,과 oldhandle은 creat, open,dup,dup2 등의 호출로 얻어진 파일 핸들이다.

반환값

새로운 파일 핸들이 성공적으로 복사 되었으면 0을 , 그렇지 않은 경우는 -1을 반환한다.  에러가 발생한 경우에는 전역변수 errno를 다음 중 하나로 설정한다.

                EMFILE    너무 많은 파일이 열려 있음.
                EBADF     부적당한 파일 번호
 

참조

_close, close, _creat, creat, cratnew, creattemp, dup, fopen, _open, open

예제

#include <sys\stat.h>
#include <string.h>
#include <fcntl.h>
#include <io.h>

int main(void)
{
  #define STDOUT 1

  int nul, oldstdout;
  char msg[] = "This is a test";

  /* create a file */
  nul = open("DUMMY.FIL", O_CREAT | O_RDWR,
  S_IREAD | S_IWRITE);

  /* create a duplicate handle for standard output */
  oldstdout = dup(STDOUT);
  /*
  redirect standard output to DUMMY.FIL
  by duplicating the file handle onto
  the file handle for standard output.
  */
  dup2(nul, STDOUT);

  /* close the handle for DUMMY.FIL */
  close(nul);

  /* will be redirected into DUMMY.FIL */
  write(STDOUT, msg, strlen(msg));

  /* restore original standard output handle */
  dup2(oldstdout, STDOUT);

  /* close duplicate handle for STDOUT */
  close(oldstdout);

  return 0;
}

 

원문

http://www.cworldlab.com/CandCplus/clibrary/dup2.htm

이 글은 스프링노트에서 작성되었습니다.

Comments