dup2()函数的使用,

时间:2024-04-15 14:04:56

#define STR "xiamanman\n"
#define STR_LEN 10
#define STDOUT 1

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
  int fd = open("./temp", O_CREAT|O_RDWR|O_APPEND);

  int s_fd = dup(STDOUT);

  dup2(fd, STDOUT);

  close(fd);

  write(STDOUT, STR, STR_LEN);

  dup2(s_fd, STDOUT);

  close(s_fd);

  write(STDOUT, STR, STR_LEN);

  printf("xx\n");

  return 0;
}

--------------------------------------------------------------------

参考资料,dup2 百度百科。主要参考英文的代码。

#define STDOUT 1

int main(void)
{

  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;
}