CreateProcess function usage in VC

Source: Internet
Author: User

1.Function Description:

WIN32API functionsCreateProcessUsed to create a new process and its main thread. This new process runs the specified executable file.

2.Function prototype:
Bool CreateProcess
(
LpctstrLpapplicationname,
LptstrLpcommandline,
Lpsecurity_attributesLpprocessattributes.
Lpsecurity_attributesLpthreadattributes,
BoolBinherithandles,
DWORDDwcreationflags,
LpvoidLpenvironment,
LpctstrLpcurrentdirectory,
LpstartupinfoLpstartupinfo,
Lpprocess_informationLpprocessinformation
);
3.Parameters:

Lpapplicationname:

A string that points to a null end and is used to specify the executable module.

This string can make the absolute or relative path of the executable module. In the latter case, the function uses the current drive and directory to create the path of the executable module.
This parameter can be set to null. In this case, the name of the executable module must be at the beginning of the lpcommandline parameter and separated by a space character from the subsequent characters.
The specified module can be a Win32 application. If the appropriate subsystem is available on the current computer, it can also be another type of module (such as MS-DOS or OS/2 ).

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

Lpcommandline:

It points to a null end and is used to specify the command line to be run.

This parameter can be blank, so the function uses the string specified by the parameter as the command line of the program to be run.

If the lpapplicationname and lpcommandline parameters are not empty, the lpapplicationname parameter specifies the module to be run, and the lpcommandline parameter specifies the command line of the module to be run. The newly running process can use the getcommandline function to obtain the entire command line. The argc and argv parameters can be used in C language programs.

If the lpapplicationname parameter is null, the first space-separated element in the string specifies the executable module name. If the file name does not include the extension name, then .exe is assumed to be the default extension. If the file name ends with a dot (.) and no extension name exists, or the file name is included in the extension, .exe will not be added to the end. If the file name does not contain a path, Windows searches for the executable file in the following order:
1. The directory of the current application.
2. Parent process directory.

3. Windows directory. You can use the getwindowsdirectory function to obtain this directory.
4. The directory listed in the PATH environment variable.
If the created process is an application based on a MS-DOS or a 16-bit windows, the lpcommandline parameter should be an absolute path to an executable file name as the first element, this can make the 32-bit windows program work well, So setting the lpcommandline parameter is the strongest.

Lpprocessattributes:

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

Lpthreadattributes:

Points to a security_attributes struct, which determines whether the returned handle can be inherited by the quilt process. If the lpthreadattributes parameter is null, the handle cannot be inherited.

Binherithandles:

Indicates whether the new process inherits the handle from the called process. If the value of the parameter is true, every inherited open handle in the calling process inherits the quilt process. The inherited handle has the same value and access permissions as the original process.

Dwcreationflags:

Specifies the additional identifier used to control the creation of priority classes and processes. The following creation flag can be combined in any way except the method listed below.

Below are some common signs.

Value:Create_default_error_mode
Meaning: the new process does not inherit the Error Mode of the called process.CreateProcessThe function provides the new process with the default error mode as an alternative. Applications can call the seterrormode function to set the current default error mode.
This flag is useful for Multithreaded Shell programs running in environments without hardware errors.
ForCreateProcessFunction. The default behavior is to inherit the caller's error mode for the new process. Set this flag to change the default processing method.
Value:Create_new_console
Meaning: a new process uses a new console instead of inheriting the console of the parent process. This flag cannot be used with the detached_process flag.
Value:Create_new_process_group
Meaning: the root process of a new process tree. All processes of the Process tree are the sub processes of the root process. The User Identifier of the new process tree is the same as that of the process, which is returned by the lpprocessinformation parameter. The generateconsolectrlevent function is often used in the process tree to send Ctrl + C or Ctrl + break signals to a group of console processes.
Value:Create_separate_wow_vdm
Meaning:(Applicable onlyWindows NT)This flag is valid only when a 16-bit windows application is running. If set, the new process runs on a private virtual DOS host (vdm. In addition, by default, all 16-bit Windows applications run in the same shared vdm as threads. The advantage of running a 16-bit program separately is that the crash of an application will only end the running of this vdm; other programs running in different vdm will continue to run normally. Similarly, the 16-bit Windows applications running in different vdm have different input queues, which means that if a program temporarily loses response, applications in independent vdm can continue to obtain input.
Value:Create_shared_wow_vdm
Meaning:(Applicable onlyWindows NT)This flag is valid only when a 16-bit windows application is running. If the defaultseparatevdm option of windows in win. ini is set to true, this identifier causes the CreateProcess function to bypass this option and run a new process on the shared virtual DOS host.
Value:Create_suincluded
Meaning: the main thread of the new process will be created in the paused State and will not run until the resumethread function is called.
Value:Create_unicode_environment
Description: If this parameter is set, the Environment block specified by the lpenvironment parameter uses Unicode characters. If it is null, the Environment block uses ANSI characters.
Value:Debug_process
Meaning: If this flag is set, the calling process will be treated as a debugging program, and the new process will be treated as a debugged process. The system notifies the debugger of all debugging events of the program to be debugged.
If you use this flag to create a process, only the process that calls the CreateProcess function can call the waitfordebugevent function.
Value:Debug_only_this_process
Meaning: If this flag is not set and the calling process is being debugged, the new process will become another debugging object of the debugger for debugging the calling process. If the calling process is not debugged, the related debugging behaviors will not be generated.
Value:Detached_process
Meaning: For console processes, the new process has no permission to access the console of the parent process. You can use the allocconsole function to create a new console. This flag cannot be used with the create_new_console flag.
The dwcreationflags parameter is also used to control the priority of a new process. The priority class is used to determine the priority of the thread scheduling of the process. If none of the following priority class labels are specified, the default priority class isNormal_priority_classUnless the created process isIdle_priority_class. In this case, the default priority of the sub-process isIdle_priority_class.
It can be one of the following signs:
Priority:High_priority_class
Meaning: indicates that the process will execute a time critical task, so it must be run immediately to ensure correctness. Programs with this priority take precedence over programs with normal or idle priority. One example is the Windows Task List. To ensure immediate response when a user calls the task, the system load is not considered. Be sure to exercise caution when using a high-priority CPU because a high-priority CPU-associated application can take up almost all of the CPU availability time.
Priority:Idle_priority_class
Meaning: indicates that the thread of the process runs only when the system is idle and can be interrupted by any high-priority task. For example, screen saver. The idle priority is inherited by the quilt process.
Priority:Normal_priority_class
Meaning: indicates that this process has no special task scheduling requirements.
Priority:Realtime_priority_class
Meaning: indicates that the process has the highest priority available. A thread with a real-time priority can interrupt the execution of all other process threads, including the system processes that are executing important tasks. For example, a real-time process with a longer execution time may cause insufficient disk cache or slow mouse response.
Lpenvironment:

Point to the Environment block of a new process. If this parameter is null, the new process uses the environment of the called process.
An environment block exists in a block consisting of a string ending with null. This block also ends with null. Each string is in the form of name = value.
Because the equal sign is used as a separator, it cannot be used as a variable name by environment variables.
Instead of using the environment block provided by the application, it is better to set this parameter to null directly, and the current directory information on the system drive will not be automatically passed to the newly created process. For more information about this situation and how to handle it, see the Notes section.
The environment block can contain Unicode or ANSI characters. If the environment block to which lpenvironment points contains Unicode characters, the create_unicode_environment flag of the dwcreationflags field will be set. If the block contains ANSI characters, the flag is cleared.
Note that an ANSI environment block ends with two zero Bytes: one is the end of the string, and the other is used to end the fast. One Unicode environment block ends with four zero bytes of oil: Two represents the end of the string, and the other two are used to end the block.

Lpcurrentdirectory:

Point to a string ending with null, which is used to indicate the working path of the child process. This string must be an absolute path containing the drive name. If this parameter is blank, the new process uses the same drive and directory as the called process. This option is the primary condition for a shell that needs to start the application and specify their drives and working directories.

Lpstartupinfo:

Point to the startupinfo struct used to determine how the new process is displayed in the main form.

Lpprocessinformation:

Point to a process_information structure used to receive the recognition information of new processes.

Return Value:
If the function is successfully executed, a non-zero value is returned.
If the function fails to be executed and zero is returned, you can use the getlasterror function to obtain additional error information.

4.Note:
CreateProcessFunction is used to run a new program. Winexec and loadmodule functions are still available, but they are also calledCreateProcessFunction implementation.

In additionCreateProcessIn addition to creating a process, a function also creates a thread object. This thread will be created together with an initialized stack. The size of the stack is determined by the description in the executable file header. The thread starts execution at the file header.

The handles of new processes and new threads are created with global access permissions. If there is no security descriptor for either of the two handles, the handle can be used in any function that requires the handle type as a parameter. When the security descriptor is provided, when the handle is used in the next step, the access permission check is always performed first. If the access permission check denies access, the requested process cannot use this handle to access this process.

This process is assigned a 32-bit process identifier. The identifier is valid until the process is aborted. It can be used to identify the process or be specified in the OpenProcess function to open the handle of the process. A 32-bit thread identifier will be allocated to the initialized thread in the process. This identifier is valid until the county seat is terminated and can be used to uniquely identify this thread in the system. These identifiers are returned in the process_information struct.

When you specify an application name in the lpapplicationname or lpcommandline parameter, whether or not the application name contains an extension name does not affect the operation. The exception is. the MS-DOS program or Windows program with COM Extension must contain. COM Extension.

You can call the waitforinputidle function to wait for the new process to complete its initialization and wait for user input. This is extremely useful for synchronization between parent and child processes, becauseCreateProcessThe function does not wait for the new process to complete its initialization. For example, a process must callWaitforinputidle.

The preferred way to end a process is to call the exitprocess function, because this function notifies all the dynamic link library (DLLs) programs of the process to end. Other methods to terminate the process do not notify the associated dynamic link library. Note that when a process calls exitprocess, other counties of the process do not have the opportunity to run any other code (including the termination code associated with the dynamic link library ).

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

* New Threads can be created during the start and DLL initialization phases, but they cannot start running until the process's dll Initialization is complete.
* There can be only one thread in the Process of DLL initialization or removal.
* After All threads initialize or unload the DLL,ExitprocessFunction.

Before all threads in a process terminate and all handles of the process and their threads are terminated by calling the closehandle function, the process will remain in the system. Both the process and the main thread handle must be calledClosehandleDisable the function. If you no longer need these handles, you 'd better close them immediately after creating the process.

When the last thread in the process is terminated, the following events occur:
* All objects opened by the process are closed.
* The termination status of a process (returned by the getexitcodeprocess function) changes from its initial value still_active to the end status of the last terminated thread.
* The thread object of the main thread is set to the flag State for other threads waiting for this object to use.
* The process object is set to the flag State for use by other threads waiting for this object.

Assume that the current directory on disk C is \ msvc \ MFC and an environment variable is called C:. Its value is c: \ msvc \ MFC, as mentioned in lpenvironmentCreateProcessWhen the lpenvironment parameter of the function is not null, It is not automatically passed to the new process. An application must manually pass the current directory information to the new process. To do this, the application must directly create environment strings and arrange them alphabetically (because Windows NT and Windows 95 use a simple environment variable ), and put them into the environment block specified in lpenvironment. Similarly, they need to find the beginning of the Environment block and repeat the sorting of the Environment block mentioned above.

One way to get the current directory variable of 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 environment data because the root directory is the default current directory of the new process on drive X.

ByCreateProcessThe handle returned by the function has the process_all_access permission on the process object.

The current directory of the sub-process object in the current directory specified by the lpcurrentdirectory parameter. The second project specified by the lpcommandline parameter is the current directory of the parent process.

5.Example:

Char chpath [301];

: Getcurrentdirectory (300, (lptstr) chpath); // obtain the current directory

Char path [200] = "\ 123.exe ";

Strcat (chpath, PATH );

Startupinfo Si;

Process_information PI;

Zeromemory (& Pi, sizeof (PI ));

Zeromemory (& Si, sizeof (SI ));

Si. cb = sizeof (SI );

// Start the child process

If (CreateProcess (chpath, "", null, null, false, 0, null, null, & Si, & PI ))

{

Closehandle (PI. hprocess );

Closehandle (PI. hthread );

}

Else

{

Afxmessagebox ("creation failed !");

Handle hprocess = getcurrentprocess (); // get current process

Terminateprocess (hprocess, 0); // close Process

}

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.