Create a pipeline in C language to implement inter-process communication

Source: Internet
Author: User
# Include <windows. h>
# Include <stdio. h>
# Include <stdlib. h>

Int Runcmd ( Char * Lpcmd)
{
Char Buf [ 2048 ] = { 0 }; // Buffer Zone
DWORD Len;
Handle hread, hwrite; // MPs queue read/write handle
Startupinfo Si;
Process_information PI;
Security_attributes SA;

// Zeromemory (BUF, 2047 );
SA. nlength = Sizeof (SA );
SA. binherithandle = true; // Pipeline handle can be inherited
SA. lpsecuritydescriptor = NULL;

// Creates an anonymous pipeline. The pipeline handle can be inherited.
If (! Createpipe (& hread, & hwrite, & SA, 2048 ))
{
Printf ( " An error occurred while creating the MPs queue! (% # X) \ n " , (Unsigned Int ) Getlasterror ());
Return 1 ;
}

Zeromemory (& Si, Sizeof (SI ));
Si. cb = Sizeof (SI );
Si. dwflags = startf_usestdhandles | startf_useshowwindow;
Si. wshowwindow = sw_hide;
Si. hstderror = hwrite;
Si. hstdoutput = hwrite;

// Create a sub-process and run commands. Sub-processes can be inherited.
If (! CreateProcess (null, lpcmd, null, null, true, 0 , Null, null, & Si, & PI ))
{
Printf ( " Failed to create process! (% # X) \ n " , (Unsigned Int ) Getlasterror ());
Closehandle (hread );
Closehandle (hwrite );
Return 1 ;
}
// The write handle has been inherited and needs to be closed locally. Otherwise, the read pipeline will be blocked.
Closehandle (hwrite );
// Read MPs queue Content and Display
While (Readfile (hread, Buf, 2047 , & Len, null ))
{
Printf (BUF );
Zeromemory (BUF, 2047 );
}
Closehandle (hread );
Return 0 ;
}

Int Main ( Int Argc, Char ** Argv)
{
Char CMD [ 256 ];
Printf ( " Enter the command line: " );
Gets (CMD );
Runcmd (CMD );
System ( " Pause " );
Return 0 ;
}

Girl does not cry (191035066) @ 19:26:50

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.