How to Use dup2

Source: Internet
Author: User
How to Use dup2-general Linux technology-Linux programming and kernel information. I have checked a lot of information about how to use dup2 and I still don't understand how the parameters are transmitted.
I want to implement the following program through dup2. Can you help me check it out?

[Table = 95%] [tr] [td]/* ---------------------- */
/* Pipe3.c */

# Include
# Include
# Include
# Include

Int main ()
{
Int data_processed;
Int file_pipes [2];
Const char some_data [] = "123 ";
Char buffer [BUFSIZ + 1];
Pid_t fork_result;

Memset (buffer, '\ 0', sizeof (buffer ));

If (pipe (file_pipes) = 0)
{
Fork_result = fork ();
If (fork_result =-1)
{
Fprintf (stderr, "Fork failure ");
Exit (EXIT_FAILURE );
}
If (fork_result = 0)
{
Sprintf (buffer, "% d", file_pipes [0]);
(Void) execl ("pipe4", "pipe4", buffer, (char *) 0 );
Exit (EXIT_FAILURE );
}
Else
{
Data_processed = write (file_pipes [1], some_data, strlen (some_data ));
Printf ("% d-wrote % d bytes \ n", (int) getpid (), data_processed );
}
}

Exit (EXIT_SUCCESS );
}
[/Td] [/tr] [/table]
[Table = 95%] [tr] [td]/* pipe4 */

# Include
# Include
# Include
# Include

Int main (int argc, char * argv [])
{
Int data_processed;

Char buffer [BUFSIZ + 1];
Int file_descriptor;

Memset (buffer, '\ 0', sizeof (buffer ));
Sscanf (argv [1], "% d", & file_descriptor );
Data_processed = read (file_descriptor, buffer, BUFSIZ );

Printf ("% d-read % d bytes: % s \ n", getpid (), data_processed, buffer );

Exit (EXIT_SUCCESS );
}
[/Td] [/tr] [/table]

Output:
$./Pipe3
980-wrote 3 bytes
981-read 3 bytes: 123

Pipe4 is called in the pipe3 program. I want to know how to implement it with dup2.

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.