WinExec, the contrast of shellexecute,createprocess

Source: Internet
Author: User

Three SDK functions: WinExec, shellexecute,createprocess can implement the requirements of calling other programs, WinExec is the simplest, ShellExecute is more flexible than winexec, CreateProcess is the most complex.
WinExec two parameters, the previous specified path, followed by a specified display mode.
ShellExecute can specify the working directory, and can also find the association of the file directly open without loading the application associated with the file, ShellExecute can also open the Web page, initiate the corresponding message association to send the message, and so on.
CreateProcess altogether has 10 parameters, but most of them can be replaced with NULL, which can specify the security properties of the process, the inheritance information, the class priority, and so on. If we want to get enough information about the new process and control the details of the new process, we need to use the CreateProcess function to achieve these goals.

Syntax for three SDK functions (WinExec, Shellexec, crateprocess):

WinExec
This function is the simplest, with only two parameters, the prototype is as follows:

UINT WinExec (
LPCSTR lpcmdline,//command path
UINT ucmdshow//display mode
);
Here's how to use it:
WinExec ("Notepad.exe", sw_show); Open Notepad
WinExec ("D://program files//test//test.exe", sw_showmaximized); Open Test.exe in a maximized manner
Note that if you use sw_showmaxmized to load a program that does not have a maximized button, such as Neterm,calc, there will be no normal form, but it has been added to the task list.

ShellExecute
The prototype is as follows:
HInstance ShellExecute (
HWND hwnd,//parent window Handle
LPCTSTR lpoperation,//operation, open mode "edit", "Explore", "open", "find", "print", "NULL"
LPCTSTR lpfile,//file name, front add path
LPCTSTR lpparameters,//Parameter
LPCTSTR lpdirectory,//default folder
INT nshowcmd//display mode
);
Here's how to use it:
ShellExecute (NULL, "open", "C://test.txt", null,null,sw_shownormal); Open C:/test.txt File
ShellExecute (NULL, "open", "http://www.google.com", NULL, NULL, SW_SHOWNORMAL); Open a webpage www.google.com
ShellExecute (NULL, "Explore", "d://c", null,null,sw_shownormal); Open Directory D:/c
ShellExecute (NULL, "print", "C://test.txt", Null,null, Sw_hide); Print File C:/test.txt
ShellExecute does not support directed output.

CreateProcess
The prototype is as follows:
BOOL CreateProcess (
LPCTSTR Lpapplicationname,//Execute program name
LPTSTR lpcommandline,//Parameter line
The following two parameters describe the security properties of the processes and threads that are created, and if NULL, the default security attributes are used
Lpsecurity_attributes lpprocessattributes,//Process security ATTRIBUTES
Lpsecurity_attributes lpthreadattributes,//thread security ATTRIBUTES
BOOL binherithandles,//Inheritance flag
DWORD dwcreationflags,//Create flag
LPVOID lpenvironment,//environment variable
LPCTSTR lpcurrentdirectory,//Run the initial directory of the process
Lpstartupinfo Lpstartupinfo,//For setting various properties when creating a child process
Lpprocess_information lpprocessinformation//For receiving information after the process has been created
);
Here's how to use it:
Process_information Pi;
Startupinfo si;
memset (&si,0,sizeof (SI));
Si.cb=sizeof (SI);
Si.wshowwindow=sw_show;
Si.dwflags=startf_useshowwindow;
BOOL Fret=createprocess ("D://putty.exe", NULL,NULL,FALSE,NULL,NULL,NULL,NULL,&SI,&PI);

As can be seen, through the above several different methods, can be implemented in the application to open other applications, some of the methods may be troublesome, so we need to choose the most suitable for their own purpose of the way to achieve their goal!


Additional notes on the three SDK functions: WinExec, Shellexecute,createprocess:
1. Define the header file
The following two header files must be defined in the header file stdafx.h:
#include <shlobj.h>//Can be replaced by windows.h
#include <shellapi.h>
If you define a header file #include <windows.h> you do not have to define #include <shlobj.h>, "windows.h" not only contains "shellapi.h", it also defines a number of data types, Without these data types, the shellapi.h itself will go wrong.

2. Define the path
The path represented in C is "//" instead of "/" as usual, so the above three functions represent a path:
Disk://directory//...//file Name
WinExec ("D://program files//test//test.exe", sw_showmaximized);
ShellExecute (NULL, "open", "C://test.txt", null,null,sw_shownormal);
BOOL Fret=createprocess ("D://putty.exe", NULL,NULL,FALSE,NULL,NULL,NULL,NULL,&AMP;SI,&AMP;PI);
//--------------------------------------------------------------------------------------------------------
BOOL CreateProcess



Lpctstrlpapplicationname,

Lptstrlpcommandline,

Lpsecurity_attributes lpprocessattributes.

Lpsecurity_attributes Lpthreadattributes,

BOOL bInheritHandles,

DWORD dwCreationFlags,

LPVOID Lpenvironment,

LPCTSTR Lpcurrentdirectory,

Lpstartupinfo Lpstartupinfo,

Lpprocess_informationlpprocessinformation

);

Edit this paragraph parameter
1.lpApplicationName:

Pointer to a null-terminated string that specifies the executable module.

This string can be an absolute path to an executable module or a relative path, in which case the function uses the current drive and directory to establish the path to the executable module.

This parameter can be set to NULL, in which case the name of the executable module must be at the front of the lpCommandLine parameter and separated by a space character from the following characters.

This specified module can be a WIN32 application. If the appropriate subsystem is available on the current computer, it can also be a different type of module (such as MS-DOS or OS/2).

In Windows NT, if the executable module is a 16-bit application, then this parameter should be set to null and the name of the executable module should be specified in the lpCommandLine parameter. A 16-bit application runs as a process on a DOS virtual machine or Windows (WOW) on a Win32.

2.lpCommandLine:

Points to a null-terminated string that specifies the command line to execute.

This parameter can be null, then the function uses the string specified by the Lpapplicationname parameter as the command line for the program to run.

If both the Lpapplicationname and lpCommandLine parameters are not empty, then the Lpapplicationname parameter specifies the module to be run, and the lpCommandLine parameter specifies the command line of the module that will be run. The new running process can use the GetCommandLine function to get the entire command line. The C language program can use the ARGC and argv parameters.

If the Lpapplicationname parameter is empty, then the first space-delimited feature in the string specifies the executable module name. If the file name does not contain an extension, then the. exe is assumed to be the default extension. If the file name ends with a dot (.) and there is no extension, or the file name contains a path, the. exe will not be added to the back. If the file name does not contain a path, Windows looks for the executable in the following order:

1). The directory of the current application.

2). The directory of the parent process.

3). Windows 95:windows system directory, which can be obtained using the GetSystemDirectory function.

Windows nt:32-bit Windows system directory. It can be obtained using the GetSystemDirectory function, and the directory name is SYSTEM32.

4). In Windows NT: 16-bit Windows system directory. This directory cannot be obtained using the WIN32 function, but it will be searched and the directory name is System.

5). Windows directory. You can use the GetWindowsDirectory function to get this directory.

6). The directory that is listed in the PATH environment variable.

If the process being created is an MS-DOS or 16-bit Windows-based application, the lpCommandLine parameter should be an absolute path to the first feature with the file name of the executable, because doing so can make 32-bit Windows programs work well, This sets the lpCommandLine parameter to be the strongest.

Note: In later versions of Visual C + + 2005, an access violation error occurs if you pass a constant pointer to the CreateProcess function as a command-line argument. This is because the system modifies the string that lpcommandline points to (such as interpreting the escape character) when it executes the function [1]. Therefore, before calling this function, you should define a temporary character array variable to hold the command-line arguments and pass the temporary variable as the lpCommandLine parameter.

Example of passing parameters:

LPTSTR szcmdline = _tcsdup (TEXT ("C:\\test.bat")),//szCmdLine the 2nd parameter, CreateProcess test pass

3.lpProcessAttributes:

Points to a security_attributes struct that determines whether the returned handle can be inherited by the quilt process. If the lpprocessattributes parameter is empty (null), then the handle cannot be inherited.

In Windows NT: The Lpsecuritydescriptor member of the security_attributes struct specifies the security descriptor for the new process, and if the argument is null, the new process uses the default security descriptor.

In Windows95: The Lpsecuritydescriptor member of the SECURITY_ATTRIBUTES structure is ignored.

4.lpThreadAttributes:

Points to a security_attributes struct that determines whether a handle to a thread that is returned can be inherited by the quilt process. If the lpthreadattributes parameter is empty (null), then the handle cannot be inherited.

In Windows NT, the Lpsecuritydescriptor member of the security_attributes struct specifies the security descriptor of the main thread, and if the argument is null, the main thread uses the default security descriptor.

In Windows95: The Lpsecuritydescriptor member of the SECURITY_ATTRIBUTES structure is ignored.

5.bInheritHandles:

Indicates whether the new process inherits a handle from the calling process.

If the value of the parameter is true, each inheritable open handle in the calling process inherits the quilt process. The inherited handle has exactly the same value and access rights as the original process.

6.dwCreationFlags:

Specifies the additional flags that are used to control the creation of priority classes and processes. The following creation flags can be specified in any combination of methods except those listed below.

(1) Value: Create_default_error_mode

Meaning: The new process does not inherit the error mode of the calling process. The CreateProcess function assigns the current default error mode to the new process as an alternative. The application can call the SetErrorMode function to set the current default error mode.

This flag is useful for multithreaded shells running in environments where there is no hardware error.

For the CreateProcess function, the default behavior is to inherit the caller's error pattern for the new process. Set this flag to change the default processing mode.

(2) Value: Create_new_console

Meaning: The new process will use a new console instead of inheriting the parent process's console. This flag cannot be used with the detached_process flag.

(3) Value: Create_new_process_group

Meaning: The new process will make the root process of a process tree. All processes in the process tree are child processes of the root process. The user identifier for the new process tree is the same as the identifier for this process, which is returned by the lpprocessinformation parameter. The process tree often uses the Generateconsolectrlevent function to allow the sending of CTRL + C or Ctrl+break signals to a set of console processes.

(4) Value: CREATE_SEPARATE_WOW_VDM

Meaning: (for Windows NT only) This flag is valid only if you are running a 16-bit Windows application. If set, the new process will run in a private virtual DOS machine (VDM). Also, by default, all 16-bit Windows applications run as threads in the same shared VDM. The advantage of running a 16-bit program alone is that an application crash will only end the operation of this VDM, and other programs running in different VDM will continue to run normally. Similarly, 16-bit Windows applications running in different VDM have different input queues, which means that if a program temporarily loses its response, the application in the standalone VDM can continue to get input.

(5) Value: CREATE_SHARED_WOW_VDM

Meaning: (for Windows NT only) This flag is valid only if you are running a 16-bit Windows application. If the DEFAULTSEPARATEVDM option for the Windows segment in Win.ini is set to true, this identity allows the CreateProcess function to cross this option and run the new process in the shared virtual DOS machine.

(6) Value: create_suspended

Meaning: The main thread of the new process is created in a paused state until the call to the ResumeThread function is called.

(7) Value: Create_unicode_enⅵronment

Meaning: If set, the environment block specified by the Lpenvironment parameter uses Unicode characters, and if empty, the environment block uses ANSI characters.

(8) Value: debug_process

Meaning: If this flag is set, the calling process will be treated as a debugger and the new process will be treated as a debugged process. The system notifies the debugger of all debug events that occur by the debugger.

If you use this flag to create a process, only the calling process (the process that calls the CreateProcess function) can call the Waitfordebugevent function.

(9) Value: debug_only_this_process

Meaning: If this flag is not set and the calling process is being debugged, the new process becomes another debug object for debugging the debugger that invokes the process. If the calling process is not debugged, the behavior about debugging is not generated.

(10) Value: detached_process

Meaning: For a console process, the new process does not have access to the parent process console. The new process can create a new console by itself through the AllocConsole function. This flag cannot be used with the CREATE_NEW_CONSOLE flag.

dwCreationFlags parameters

It is also used to control the priority class of the new process, which is used to prioritize the thread scheduling for this process. If the following priority class flags are not specified, then the default priority class is Normal_priority_class unless the process being created is idle_priority_class. In this scenario, the default priority class for the process is idle_priority_class.

One of the following flags can be used:

Priority: High_priority_class

Meaning: Indicates that the process will perform a time-critical task, so it must be run immediately to ensure that it is correct. This priority program takes precedence over normal priority or idle priority programs. An example is the Windows Task List, which gives the system load consideration in order to ensure that the user can respond immediately when the call is made. Be cautious when using high-priority because a high-priority CPU affiliate application can consume almost all of the CPU's available time.

Priority: Idle_priority_class

Meaning: The thread that indicates this process will run only when the system is idle and can be interrupted by any high-priority task. For example, a screen saver. The idle priority is inherited by the quilt process.

Priority: Normal_priority_class

Meaning: Indicates that the process does not have a special task scheduling requirement.

Priority: Realtime_priority_class

Meaning: Indicates that the process has the highest priority available. A thread with a process with a real-time priority can interrupt the execution of all other process threads, including system processes that are performing important tasks. For example, a real-time process with a slightly longer execution time may result in insufficient disk cache or slow mouse reflection.

7.lpEnvironment:

The environment block that points to a new process. If this parameter is empty, the new process uses the environment that invokes the process.

An environment block exists in a block that consists of a null-terminated string, and this block is also null-terminated. Each string is in the form of a name=value.

Because the equality flag is treated as a delimiter, it cannot be used as a variable name by an environment variable.

Instead of using the environment block provided by the application, set this parameter directly to NULL, and the current directory information on the system drive is not automatically passed to the newly created process. For a discussion of this situation and how to deal with it, see the comments section.

The environment block can contain Unicode or ANSI characters. If lpenvironment points to an environment block that contains UNICODE characters, the create_unicode_enⅵronment flag for the dwCreationFlags field is set. If the block contains ANSI characters, the flag is emptied.

Note that an ANSI environment block is terminated by two 0 bytes: One is the end of the string and the other is used to end this fast. A Unicode environment block is terminated by four 0 bytes: Two represents the end of a string and two is used to end the block.

8.lpCurrentDirectory:

Points to a null-terminated string that is used to specify the working path of the child process. This string must be an absolute path that contains the drive name. If this parameter is NULL, the new process will use the same drive and directory as the calling process. This option is a primary condition that requires the shell to launch applications and specify their drive and working directory.

9.lpStartupInfo:

Points to a STARTUPINFO structure that determines how the main form of a new process is displayed.

10.lpProcessInformation:

Points to a process_information structure that receives identifying information for a new process.

Edit this paragraph return value
If the function executes successfully, returns a value other than 0.

If the function fails to execute and returns zero, you can use the GetLastError function to obtain additional information about the error.

Comments:

The CreateProcess function is used to run a new program. The winexec and LoadModule functions are still available, but they are also implemented by calling the CreateProcess function.

In addition to creating a process, the CreateProcess function also creates a thread object. This thread is created along with an initialized stack, and the size of the stack is determined by the description in the file header of the executable file. Threads are executed at the beginning of the file header.

A handle to a new process and a new thread is created with global access rights. For any of these two handles, if there is no security descriptor, the handle can be used in any function that requires a handle type as a parameter. When a security descriptor is provided, the next time the handle is used, the access permission is always checked, and if access is denied access, the requested process will not be able to access the process using that handle.

This process is assigned to a 32-bit process identifier. The identifier is valid until the process aborts. It can be used to identify the process, or be specified in the OpenProcess function to open a handle to the process. Threads that are initialized in the process are assigned a 32-bit thread identifier. This identifier is valid until the thread abort and can be used to uniquely identify the thread in the system. These identifiers are returned in the process_information structure.

When you specify an application name in the Lpapplicationname or lpcommandline parameter, whether the application name contains an extension does not affect the run, There is only one case exception: an MS-DOS program or a Windows program that has a. com extension must contain a. com extension.

The calling process can wait for the new process to complete its initialization and wait for user input through the WaitForInputIdle function. This is extremely useful for synchronization between the parent and child processes, because the CreateProcess function does not wait for the new process to complete its initialization work. For example, before attempting to associate a window with a new process, the process should call WaitForInputIdle first.

The preferred way to end a process is to call the ExitProcess function, because this function notifies the process that all dynamic link library (DLLs) programs have entered the end state. Other methods of ending a process do not notify the associated dynamic-link library. Note When a process calls ExitProcess, other threads of the process do not have the opportunity to run any other code (including the terminating code of the associated dynamic-link library).

Exitprocess,exitthread,createthread,createremotethread, when a process is started (the result of a call to CreateProcess) is serialized in the process. In an address space, only one of these events can occur within the same time. This means that the following restrictions will be retained:

* During the process startup and DLL initialization phases, new threads can be created, but they cannot start running until the process's DLL initialization is complete.

* There can be only one thread in a process in a DLL initialization or removal routine.

* The ExitProcess function does not return until all threads have finished initializing or removing the DLL.

The process is left in the system until all threads in the process are terminated and the process's handles and their threads are terminated by calling the CloseHandle function. Both the process and the handle of the main thread must be closed by calling the CloseHandle function. If these handles are no longer needed, it is a good idea to close them immediately after the process is created.

When the last thread in the process terminates, the following events occur:

* All objects opened by the process will be closed.

* The terminating state of the process (returned by the GetExitCodeProcess function) changes from its initial value still_actⅳe to the end state of the last terminated thread.

* Thread objects on the main thread are set to flag State for use by other threads waiting for this object.

* The Process object is set to the flag State for use by other threads waiting for this object.

Assuming that the current directory on the C drive is \MSVC\MFC and has an environment variable called C:, its value is C:\MSVC\MFC, as mentioned in the previous lpenvironment, Directory information on such a system drive will not be automatically passed into the new process if the lpenvironment parameter of the CreateProcess function is not empty. An application must manually pass the current directory information to the new process. To do this, the application must create the environment strings directly and arrange them alphabetically (because Windows NT and Windows 95 use a shorthand environment variable) and put them into the environment block specified in Lpenvironment. Similarly, they want to find the beginning of the environment block and repeat the order of the environment blocks mentioned earlier.

One way to get the current directory variable for drive X is to call Getfullpathname ("x:",.. )。 This avoids the need for an application to scan the environment block. If the absolute path returned is x:\, you do not need to pass this value as an ambient data, because the root directory is the default current directory for the new process on drive X.

The handle returned by the CreateProcess function has process_all_access access to the Process object.

The current directory of the current directory room child process object specified by the Lpcurrentdirectory parameter. The second item specified by the lpCommandLine parameter is the current directory of the parent process.

For Windows NT, when a process is created with the specified Create_new_process_group, a call to SetConsoleCtrlHandler (Null,true) is used on the new process. This means that the CTRL + C is not valid for the new process. This allows the upper-level surgical procedures to handle CTRL + C information on their own and selectively pass these signals to the child process. The ctrl+break is still valid and can be used to interrupt the execution of the process/process tree.

Security Notes:

The first parameter, Lpapplicationname, may be empty, in which case the name of the executable file must be in lpCommandLine, and the lpCommandLine parameter can contain spaces. If the executable file or path contains spaces, then there is a risk of executing the incorrect file, due to the way the function parses the whitespace. For example, the following example is dangerous because it tries to run the Program.exe file, and if the file exists, it will replace the MyApp.exe file.

CreateProcess (NULL, "C:\\Program Files\\myapp.exe", ...)

If a malicious user writes a file named Program.exe in the system, then any call to the CreateProcess function and the parameters of the Program Files folder are used in the file path, It is possible to run the Program.exe file instead of running the file that you intended to run.

To avoid this problem, you can not pass a null value to the Lpapplicationname parameter, or enclose the full pathname of the executable in lpcommandline with double quotation marks (escape characters), as follows:

CreateProcess (NULL, "\" C:\\Program files\\myapp.exe\ "-l-s", ...)

-L and-s are the parameters of the MyApp.exe executable file.

Finally, the point is: in the lpapplicationname parameters and lpcommandline The first parameter is the same, some people say it seems a bit repetitive, in fact, this is a purely recognized habit!

See

Allocconsole,closehandle,createremotethread,createthread,exitprocess,exitthread,generateconsolectrlevent, Getcommandline,getenvironmentstrings,getexitcodeprocess,getfullpathname,getstartupinfo,getsystemdirectory, Getwindowsdirectory,loadmodule,openprocess,process_information,resumethread,security_attributes, Setconsolectrlhandler,seterrormode,startupinfo,terminateprocess,waitforinputidle,waitfordebugevent,winexec

Quick Info:

Import Library: Kernel32.lib

Header file: Winbase.h

Edit this paragraph to illustrate
C code
#include <stdio.h>

#include <windows.h>

int main (int argc,char *argv[])

{

Char szcommandline[] = "Notepad";

Startupinfo si = {sizeof (SI)};

Process_information Pi;

Si.dwflags = Startf_useshowwindow; Specifies that the Wshowwindow member is valid

Si.wshowwindow = TRUE; If this member is set to true, the main window of the new process is displayed

BOOL BRet = CreateProcess (

null,//do not specify the file name of the executable here

szcommandline,//command-line arguments

null,//Default Process Security

null,//Default Process Security

false,//specifies that the current in-process handle cannot be inherited by the quilt process

create_new_console,//Creating a new console window for a new process

null,//environment variables that use this process

null,//drives and directories that use this process

&si,

&AMP;PI);

if (BRet)

{

Do not use the handle best off

CloseHandle (Pi.hthread);

CloseHandle (pi.hprocess);

printf ("ID number of the new process:%d\n", pi.dwprocessid);

printf ("The new process's main thread ID number:%d\n", Pi.dwthreadid);

}

return 0;

}
C + + code
#include <iostream>

#include <windows.h>

using namespace Std;

int main ()

{

Startupinfo si; Some of the required parameter settings

memset (&si,0,sizeof (startupinfo));

SI.CB = sizeof (STARTUPINFO);

Si.dwflags = Startf_useshowwindow;

Si.wshowwindow = Sw_show;

Process_information Pi; End of required parameters setting

if (! CreateProcess ("C:\\windows\\system32\\notepad.exe", Null,null,null,false,0,null,null,&si,&pi))

{

cout<< "Create fail!" <<endl;

Exit (1);

}

Else

{

cout<< "Success!" <<endl;

}

return 0;

}

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.