Dup/dup2 Output redirect

Source: Internet
Author: User

Function Prototypes:
#include
int dup (int oldfd);
int dup2 (int oldfd,int newfd);
The DUP is used to replicate the file descriptors referred to by OLDFD. However, when replication succeeds, the smallest file descriptor that has not been used is returned. Returns 1 if there is an error, and the error code is stored in errno. The new file descriptor and parameters returned OLDFD point to the same file, share all the locks, read and write pointers, and various permissions or flags. .h>

1. Open a new file .h>

2. Turn off the standard output file symbol .h>

3. Call the DUP to the file descriptor .h>

4. When the file descriptor changes to 1.h>

5. Redirect the data you want to print to a file. .h>

#include <stdio.h>                                                                           #include <stdlib.h> #include <errno.h> #include <string.h> #include <unistd.h># include<fcntl.h> #include <sys/stat.h> #define  _PATH_FILE_   "./log" Int main () {     umask (0);     int fd=open (_path_file_,o_creat| o_rdwr,0644)     if (fd<0) {        perror ("open" );        return 1;    }     close (1);     int&Nbsp;new_fd=dup (FD);     close (FD);    int count=0;     while (count++<100)     {         printf ("helo world\n");     }    fflush (stdout);//must, printf redirected to full buffer, buffer full before flushing, resulting in file     close (NEW_FD) not written;     return 0;}


This article is from the "Small Stop" blog, please be sure to keep this source http://10541556.blog.51cto.com/10531556/1775692

Dup/dup2 Output redirect

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.