Linux Knowledge Review 1-dup dup2

Source: Internet
Author: User

#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.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); Replication for subsequent recoveries
/*
REDIRECT standard output to Dummy.fil
By duplicating the file handle onto the
File handle for standard output.
*/
Dup2 (nul, STDOUT); REDIRECT standard output to Nul
/* Close the handle for Dummy.fil */
Close (NUL);
/* 'll be redirected into Dummy.fil */
Write (STDOUT, MSG, strlen (msg));
/* Restore original standard output
HANDLE * *
Dup2 (Oldstdout, STDOUT); REDIRECT standard output to previously saved standard output
/* Close duplicate handle for STDOUT */
Close (oldstdout);
return 0;
}

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

FD----File Table----Vnode

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

Point to relationship change:

DUP (Oldstdout, STDOUT)

Oldstdout points to the file table of the stdout;

Dup2 (nul, STDOUT)

StdOut points to the file table of the NUL;

Dup2 (Oldstdout, STDOUT)

StdOut points to the file table saved by Oldstdout;

Detailed reference:

Http://www.cnblogs.com/GODYCA/archive/2013/01/05/2846197.html

Linux Knowledge Review 1-dup dup2

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.