VC obtains external program execution results

Source: Internet
Author: User

You should be familiar with calling external programs on VC, such as ShellExecute and CreateProcess.


System ("D: // adb.exe devices> C: // temp.txt ");


ShellExecute (null, "open", "adb.exe", "devices", "d: //", sw_show );


Startupinfo Si;
Process_information PI;

CreateProcess (null, "d: // famos // adb.exe devices"
, Null, null, true, null, & Si, & PI );

If you only execute external programs, these methods are enough, but sometimes you will encounter execution of external programs and get their execution results. People who have done QT should know that to implement the same function, they only need to call the class qprocess, but this is not the case in VC. This is only known after the information is found today. The specific is to use the pipeline to read, Here reprinted by others to write a very clear article on the results of the post, for everyone to learn together, the article Source: feino Network (

The details are as follows:



I wonder if you have used such a program. They do not have the decompression function, but call the DOS program PKZIP to decompress the zip package. However, when the program is running, there is no dos Console window and all the information that should have been displayed under DOS appears in the text box of the installer. This design is both beautiful and can prevent a few users who are eye-catching from closing your DOS window in advance.

Now let's discuss how to use the anonymous pipeline technology to implement this function.

Pipeline technology has been around for a long time. I believe many people are most familiar with the pipeline technology in the DOS command. When we type a file, we can input it if we want it to be paged.

C:/> type autoexec. Bat | more

Here "|" is the pipeline operator. It uses the type output information as the Reading end and the more input end as the pipeline established by the writing end.

In Windows, a large number of pipelines are also anonymous pipelines, which are created using the createpipe API function.
Program code
Bool createpipe (
Phandle hreadpipe, // pointer to the read-side handle
Phandle hwritepipe, // pointer to the write handle
Lpsecurity_attributes lppipeattributes, // pointer to the Security Attribute Structure
DWORD nsize // MPs queue capacity

In the preceding parameters, note that hreadpipe, hwritepipe, is the pointer to the handle, rather than the handle (I used it wrong for the first time ). Nsize is generally set to 0 so that the system determines the pipeline capacity. Now let's look at the security attribute structure, security_attributes.
Program code
Typedef struct _ security_attributes {// SA
DWORD nlength;
Lpvoid lpsecuritydescriptor;
Bool binherithandle;
} Security_attributes;

NLength is the size of the struct, which is naturally obtained using sizeof. LpSecurityDescriptor is a security descriptor (a C-Style string ). BInheritHandle indicates whether the security description object can be inherited by the newly created process. Don't worry about their specific meaning. You will naturally know it when using it.

Okay. Now let's create a pipeline.
Program code
HANDLE hReadPipe, hWritePipe;

Sa. nLength = sizeof (SECURITY_ATTRIBUTES );
Sa. lpSecurityDescriptor = NULL; file: // use the default security descriptor of the system.
Sa. bInheritHandle = TRUE; file: // it must be TRUE. Otherwise, the handle cannot be inherited.
CreeatePipe (& hReadPipe, & hWritePipe, & sa, 0 );

Our pipeline has been built. Of course, this is not the ultimate goal. Our goal is to redirect the output of a program on DOS to the Edit Control of a Windows program. So we still need to start a DOS program first, and there is no window in the DOS Console (otherwise, we will not reveal it ). We use CreateProcess to create a DOS program process.

Program code

BOOL CreateProcess (
Lptstr lpApplicationName, // C-style string: Application name
LPTSTR lpCommandLine, // C-style string: executed command
LPSECURITY_ATTRIBUTES lpProcessAttributes, // process Security Attribute
Lpsecurity_attributes lpthreadattributes, // thread Security Attribute
Bool binherithandles, // whether to inherit the HANDLE flag
DWORD dwcreationflags, // create a flag
Lpvoid lpenvironment, // C-style string: Environment Settings
Maid directory, // C-style string: Execution directory
Lpstartupinfo, // start information
Lpprocess_information lpprocessinformation // Process Information

Don't go first. The parameter is a little more, but most of them do not need to fill in or leave a null parameter. Lpapplication can be used at any time. Lpcommandline but the commands you want to execute must be carefully written. Let's see how to set lpprocessattributes and lpthreadattributes. Ah? This is the one you just mentioned. Yes, but it is simpler than just now. Since we only create a process and whether it can be inherited or not, the two values are all null. Binherithandles must also be set to true, because since we want a new process to output information to the process that calls it, we must let the new process inherit the handle of the calling process. We have no requirement on the newly created process, so dwcreationflags is null. According to your own requirements, lpenvironment and lpcurrentdirectory are just a bit simple. Generally, they are also null. The next lpstartupinfo is the key. Let's take a closer look.
Program code
Typedef struct _ startupinfo {// Si
Dword cb;
Lptstr lpreserved;
LPTSTR lpDesktop;
LPTSTR lpTitle;
DWORD dwXSize;
DWORD dwYSize;
DWORD dwXCountChars;
DWORD dwYCountChars;
DWORD dwFillAttribute;
DWORD dwFlags;
WORD wShowWindow;
WORD cbReserved2;
LPBYTE lpReserved2;
HANDLE hStdInput;
HANDLE hStdOutput;
HANDLE hStdError;

If there are so many parameters, one write will surely be exhausted. That's right, MS has long thought it would be exhausting. Therefore, it provides the life-saving API function GetStartupInfo.
Program code
VOID GetStartupInfo (

This function is used to obtain the StartupInfo of the current process. The newly created process is basically the same as the StartupInfo of the current process. just borrow it. Then you can make a small modification.
Here are a few changes: cb, dwFlags, hStdOutput, hStdError, and wShowWindow. Let's talk about cb. It refers to the size of STARTUPINFO or the sizeof method. Besides, wShowWindow sets the real state of the window when the new process is created. This property is of course for SW_HIDE. Aren't we going to hide the newly created DOS process. Haha, see hStdOutput and hStdError, standard output and error output handle. The key point is that as long as we set these two handles to hWrite, our processes will be written into the newly established anonymous pipeline once there is a standard output, we can use the hReadPipe handle of the pipeline to read the content and write it into the Edit Control. It's really easy to say. After these key parameters are completed, do not forget dwFlags. This parameter is used to specify the value of this heap parameter in STARTUPINFO. Now that we use hStdOutput, hStdError, and wShowWindow, dwFlags will give STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES.

Return to the last parameter lpProcessInformation (tired!) of CreateProcess !). You don't need to fill in this parameter. It is the information returned by CreateProcess. You just need to give him the address of the PROCESS_INFORMATION structure case.

This is a big success. one end of the pipeline is connected to the standard output end of the new process, and one end can be read by itself using the API function ReadFile. Wait, no. Our pipeline is still faulty. After hWrite is given to hStdOutput and hStdError, a pipeline write end will be opened in the new process when the new process starts, when CreatePipe is used in the current process to create an MPS queue, hWrite is also available in the current process. Well, there is a malformed pipe with two writing ends and one reading end. There must be a problem with such pipelines. Since the current process does not use the write end, we must disable the write end of the current process. In this way, our pipeline is truly successful. Let's take a look at the source program written by VC ++:
Program code
* Use the MPs queue technology to change the dir /? To a CEdit control of the MFC application.
* VC ++ 6.0 + WinXP
* Detrox, 2003.

Void CPipeDlg: OnButton1 ()
HANDLE hRead, hWrite;

Sa. nLength = sizeof (SECURITY_ATTRIBUTES );
Sa. lpSecurityDescriptor = NULL;
Sa. bInheritHandle = TRUE;
If (! CreatePipe (& hRead, & hWrite, & sa, 0 )){
MessageBox ("Error On CreatePipe ()");
Si. cb = sizeof (STARTUPINFO );
GetStartupInfo (& si );
Si. hStdError = hWrite;
Si. hStdOutput = hWrite;
Si. wShowWindow = SW_HIDE;
Si. dwflags = startf_useshowwindow | startf_usestdhandles;
If (! CreateProcess (null, "C: // windows // system32 // cmd.exe/c dir /? "
, Null, null, true, null, & Si, & PI )){
MessageBox ("error on CreateProcess ()");
Closehandle (hwrite );

Char buffer [4096] = {0 };
DWORD bytesread;
While (true ){
If (readfile (hread, buffer, 4095, & bytesread, null) = NULL)
M_edit1 + = buffer;
Updatedata (false );
Sleep (200 );

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: 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.