CreateProcess Function Description

Source: Internet
Author: User

CreateProcess
Note:
The CreateProcess function of WIN32API is used to create a new process and its main thread. The new process executes the specified executable file.

Function prototype:
Bool CreateProcess
(
Lptstr lpapplicationname,
Lptstr lpcommandline,
Lpsecurity_attributes lpprocessattributes.
Lpsecurity_attributes lpthreadattributes,
Bool binherithandles,
DWORD dwcreationflags,
Lpvoid lpenvironment,
Maid directory,
Lpstartupinfo,
Lpprocess_information lpprocessinformation
);

 

A thread calls it to create a process kernel object. The process kernel object is used to manage the new process. Then, the system creates a virtual address space for the new process, load the code and data of the executable files (and DLL) to this address space, and then the system creates a thread kernel object for the new main thread.

 

First, describe lpapplicationname and lpcommandline.

 

Lpapplicationname and lpcommandline point to the name of the executable file to be used by the new process and the command line string to be passed to the new process, respectively. The lpcommandline type is lptstr, Which is internal, createProcess actually changes the command line string we pass to it. Of course, it restores this string before it returns, so this code is wrong:

Startupinfo Si = {sizeof (SI)}; process_information PI; CreateProcess (null, text ("Notepad"), null, null, false, 0, null, null, & Si, & PI );

The solution to this bug is to copy the constant string to a temporary buffer, as shown below:

Startupinfo Si = {sizeof (SI)}; process_information PI; tchar szcommandline [] = text ("Notepad"); CreateProcess (null, szcommandline, null, null, false, 0, null, null, & Si, & PI );

Therefore, we hope Microsoft can correct the future version number in windows and create a temporary copy of the string. Let's free it.

 

 

Two statuses:

1: lpapplicationname is null, (99% is set to null)

In this case, the name of the runable module must be at the beginning of the lpcommandline limit and separated by a space character. When CreateProcess parses lpcommandline limit, in addition, if the file name does not contain a complete path, CreateProcess searches for executable files in the following order:

(1) The folder where the .exe file is located

(2) The current folder of the main process

(3) Windows system folder, that is, the System32 subfolder returned by getsystemdirectory

(4) Windows Folder

(5) folders listed in Path Environment Variables

2: lpapplicationname is not null

In this case, the file extension must be specified. The system does not assume that the extension is automatically assumed as 1, and the file name does not include a complete path, createProcess only searches for executable files in the current directory and does not search for files in any other folder.

 

Once the system finds the executable file, it creates a new process, maps the code and data of the executable file to the address space of the new process, and then starts the routine, c/C ++ transmits the address of the first real-time vertex after the name of the executable file to the number of psz1_line partitions of (W) winmain.

 

Next, we will explain lpprocessattributes and lpthreadattributes.

To create a new process, the system must create a thread Kernel Object of the Process kernel object and the main thread of the new process, the two shards indicate the security descriptors of these two kernel objects.

 

 

Not to mention binherithandles. Set the parent-child process handle to describe the table's inheritance.

 

 

Dwcreationflags identifies a flag that affects the creation METHOD OF A NEW PROCESS

 

Value: create_default_error_mode
Meaning: the new process does not inherit the Error Mode of the called process. The CreateProcess function allows the new process to replace the current default error mode. The application can call the seterrormode function to set the current default error mode.
This flag is useful for multi-threaded Shell programs that run in environments without hardware errors.
For the CreateProcess function, 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 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 number of lpprocessinformation tokens. The process tree often uses the generateconsolectrlevent function to agree to send Ctrl + C or Ctrl + break signals to a group of console processes.

Value: create_separate_wow_vdm
Meaning: (only applicable to Windows NT) this flag is valid only when a 16-bit windows application is executed. If it is set, the new process will be executed on a private virtual DOS host (vdm. In addition, by default, all 16-bit Windows applications are executed in the same shared vdm in the thread mode. The advantage of executing a 16-bit program separately is that an application crash will only end the execution of this vdm; other programs executed in different vdm will continue to run normally. Similarly, the 16-bit Windows applications executed in different vdm have different input queues, which means assuming that a program temporarily loses response, applications in independent vdm can continue to obtain input.

Value: create_shared_wow_vdm
Meaning: (only applicable to Windows NT) this flag is valid only when a 16-bit windows application is executed. Assuming that the defaultseparatevdm option of windows in win. ini is set to true, this identifier causes the CreateProcess function to bypass this option and execute a new process on the shared virtual DOS host.

Value: create_suincluded
Meaning: the main thread of the new process will be suspended after being created until the call to the resumethread function is called. In this way, the parent process can change the memory in the address space of the child process, change the priority of the main thread of the child process, or add it to a job before the process runs whatever code. After the parent process changes the child process, then, call resumethread to approve the sub-process code.

Value: create_unicode_environment
Description: it is set to use Unicode characters for the Environment block specified by the number of lpenvironment blocks. 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 for the debugger to debug the calling process. If the calling process is not debugged, the debugging behavior will not be generated.

Value: detached_process
Meaning: For console processes, the new process does not have the permission to ask the parent process console. The new process can use the allocconsole function to create a new console. This flag cannot be used with the create_new_console flag.

The number of dwcreationflags workers is also used to control the priority of the 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 is normal_priority_class unless the created process is idle_priority_class. In this case, the default priority class of the sub-process is idle_priority_class.
One of the following logos is possible:

Priority: high_priority_class
Meaning: indicates that the process will execute a time critical task, so it must be executed immediately to ensure correctness. Programs with this priority take precedence over programs with normal or empty priorities. One example is the Windows Task List. To ensure immediate response when a user calls the task, the system load is not considered. Make sure that you are careful when using a high-priority CPU because a high-priority CPU-related application can take up almost all the CPU availability time.

Priority: idle_priority_class
Meaning: indicates that the thread of this process can be executed only when the system is busy and can be interrupted by any high-priority task. For example, screen saver. The idle priority will be 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 running of all other process threads, including the system processes that are running important tasks. For example, a real-time process with a longer running time may cause insufficient disk cache or slow mouse response.

 

Lpenvironment:

 

Point to the Environment block of a new process. Assuming that the number of workers is null, the new process uses the environment that calls the 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 the number of partitions to null, and the current Folder Information on the system drive will not be automatically transmitted to the newly created process. For more information about this situation and how to handle it, see the stare section.
The environment block can contain Unicode or ANSI characters. Assume that the Environment block to which lpenvironment points includes 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 the number of partitions is null, the new process uses the same drive and folder as the calling process. This option is the primary condition for a shell that needs to start the application and specify their drives and working folders.

 

 

 

Lpstartupinfo:

Typedef struct _ startupinfo {dword cb; lptstr lpreserved; lptstr lpdesktop; lptstr lptitle; DWORD dwx; DWORD dwy; DWORD dwxsize; DWORD dwysize; DWORD frequency; DWORD dwflags; Word wshowwindow; Word cbreserved2; lpbyte lpreserved2; handle hstdinput; handle hstdoutput; handle hstderror;} startupinfo, * lpstartupinfo;

 

Point to the startupinfo struct used to determine how the new process's main window is displayed.

Most applications only use the default value to generate an application. At the very least, they need to initialize all the applications to 0, and then set the CB member to the size of the struct. If there is no clear 0, the new process may fail to be created.

 

 

Table 4-6 startupinfo structure members

Member Form, console or both Function
CB Both Including the number of bytes in the S ta RT u p I n f O structure. Assuming that m I c r o s o f t will expand the structure in the future, it can be used as a version number control method. The application must initialize c B to s I z e o f (s ta RT u p I n f o)
Lpreserved Both Retained. Must be initialized to n u L
Lpdesktop Both Used to identify the name of the desktop where the application is started. If the desktop exists, the new process is associated with the specified desktop. If the desktop does not exist, create a desktop with the default attribute and use the name specified for the new process. Assume that L p D e s k t o p is n u L (this is the most common case), then the process will be associated with the current desktop
Lptitle Console Used to set the name of the console form. If l p ti t l e is n u l, the name of the executable file will be used as the form name.
Dwx
Dwy
Both It is used to set the X and Y coordinates (in pixels) of the position where the application form should be placed on the screen ). Only when the sub-process uses c w _ u s e d e fa u lt as the number of X Workers of C r e a t e wi n d o w to create its first overlap form, these two coordinates are used. If you create an application for a console form, these members are used to specify the upper left corner of the console form.
Dwxsize Both Used to set the width and length of an application form (in pixels) only dwysize is available. When the sub-process uses c w _ u s e d e fa u lt as the number of N wi d t h workers of C r e t e wi n d o W when its first overlapping form, to use these values. If you create an application for a console form, these members are used to specify the width of the console form.
Dwxcountchars
Dwycountchars
Console Used to set the width and height of the console form of the sub-application (in characters)
Dwfillattribute Console Used to set the text and background colors used by the console form of the sub-Application
Dwflags Both For more information, see the following section and Table 4-7.
Wshowwindow Form It is used to set the s h o w wi n d o w that is first called by the sub-application to use s w _ s h o w d e fa u lt as n C M D S H O W when the number of workers is passed, how should the first overlapping form of the application appear. This member can be an identifier of s w _ * that is often used in the show wi n d o W function.
Cbreserved2 Both Retained. Must be initialized to 0
Lpreserved2 Both Retained. Must be initialized to n u L
Hstdinput
Hstdoutput
Hstderror
Console Used to set the cache handle for console input and output. According to the default settings, h s t d I n P U T is used to identify the keyboard cache, h s t d o u t p u t and h s t d e r o r are used to identify the cache of the console form

 

 

 

Dwflags contains a group of flags. Most flags only tell the CreateProcess function. Other startupinfo members include useful information or ignore some members.

 

Table 4-7 use signs and meanings

Flag Description
Startf_usesize Use d w x s I z e and d w y s I Z E members
Startf_useshowwindow Use w s h o w wi n d o W members
Startf_useposition Use members d w x and D W Y
Startf_usecountchars Use d w x c o u n t c h a r s and dwycount chars members
Startf_usefillattribute Use d w f I l a t r I B u t e Member
Startf_usestdhandles Use h s t d I n P U T, H S T d o u t p U T and H S T d e r o r members
Startf_run_fullscreen The console application that is forcibly executed on Computer X 8 6 is started and executed in full screen mode.

 

 

There are also two signs: startf_orceonfeedback and startfforceofffeedback. when starting a new process, they can be used to control the mouse cursor, because Windows supports real multi-task preemptible execution, therefore, you can start an application and use another program during process initialization. To provide visual feedback to users, CreateProcess will temporarily change the system cursor to a new one,

If startf_orceonfeedback is specified, CreateProcess does not change the cursor.

If startfforceofffeedback is specified, CreateProcess changes the new cursor. After 2 seconds, if the new process is not running, no matter What gui call, the cursor is restored. If a GUI call is run, the form must be displayed within 5 seconds. Otherwise, the cursor is restored,

Lpstartupinfo

 

 

Point to the required process_information struct

Typedef struct _ process_information {handle hprocess; handle hthread; DWORD dwprocessid; DWORD dwthreadid;} process_information;

As described above, creating a new process allows the system to establish a process kernel object and a thread kernel object. When creating a process, the system assigns an initial count value of 1 to each object, then, before CreateProcess returns, this function opens the process kernel object and the thread kernel object, and places the process-related handle of each object in hprocess and hthread in _ process_information, when CreateProcess opens these objects internally, the Count of each object changes to 2.

 

Therefore, you must disable the sub-process and its main thread handle to avoid resource leakage during application execution. Of course, when the process is terminated, the system automatically eliminates these leaks, however, when a process no longer needs to ask the sub-process and its threads, the well-written software can display and close these handles (by calling the closehandle function ), the failure to close these handles is one of the most common mistakes made by developers.

 

When a process and thread kernel object are created, the system gives the object a unique ID within the system. The process ID and thread ID share the same number pool, this means that the process and thread cannot have the same ID, and the ID cannot be 0. Similarly, when CreateProcess returns, dwprocessid and dwthreadid are filled, id allows you to easily identify processes and threads in the system. Some useful tools (such as task manager) use the most IDs, while efficient applications use very little, for this reason, most applications ignore IDs completely.

 

If the application uses the ID to track processes and threads, it must understand that the system will immediately reuse the process ID and thread ID. For example, when a process is created, the ID value is 122, if another new process object is created, the system will not assign the same ID to it. However, if the first process object is released, the system will be able to assign 122 to the next process object created, therefore, if an application wants to communicate with its "creator", it is best not to use the ID. It should define a mechanism with better durability, such as kernel objects and form handles.

 

 

Suppose you want to create a new process and wait for the result. The following code can be used:

Process_information PI; DWORD dwexitcode; // spawn the child process. bool fsuccess = CreateProcess (..., π); If (fsuccess) {// close the thread handle as soon as // it is no longer needed! Closehandle (Pi. hthread); // suspend our execution until // The child has terminated. waitforsingleobject (Pi. hprocess, infinite); // The child process terminated; // get its exit code. getexitcodeprocess (Pi. hprocess, & dwexitcode); // close the Process Handle as soon as // it is no longer needed. closehandle (Pi. hprocess );}

It must be noted that only when the process object is terminated, waitforsingleobject can be notified. Therefore, the call to waitforsingleobject will suspend the thread of the parent process until the child process is terminated and executed, when waitforsingleobject is returned, the exit code of the sub-process can be obtained through getexitcodeprocess.

 

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

In addition, the CreateProcess function creates a process and 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 file header of the runable file. The thread starts to run at the beginning of the file header.

The handles of new processes and new threads are created with the global issue permission. For any of the two handles, if there is no secure descriptor, the handle can be used in any function that requires the handle type as the number of descriptors. When a security descriptor is provided, when the handle is used in the next step, the system will always first check the allow permission. Assume that the allow permission check rejects the allow permission check, the requested process cannot use this handle to notify 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 the application name is specified in the lpapplicationname or lpcommandline parameter, whether or not the application name contains the extension name does not affect the execution. There is only one exception. MS-DOS programs or Windows programs whose COM is extension must include. COM Extension.

The call process can use the waitforinputidle function to wait for the initialization of the new process and wait for user input. This is extremely useful for synchronization between parent and child processes, because the CreateProcess function will not wait for the initialization of the new process to complete. For example, before trying to associate a form with a new process, the process should call waitforinputidle.

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

Exitprocess, exitthread, createthread, and createremotethread are serialized in the process when a process is started (the CreateProcess result is called. 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 be started until the process's dll Initialization is complete.
* There is only one thread in the Process of DLL initialization or removal routines.
* The exitprocess function will not return until all threads have completed DLL initialization or removal.

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 process and main thread handles must be closed by calling the closehandle function. If you no longer need these handles, it is best to immediately close them 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.
* The process object is set to the flag State for use by other threads waiting for this object.

If the current folder on drive C is/msvc/MFC and an environment variable is called C:, its value is C:/msvc/mfc, as previously mentioned in lpenvironment, The Folder Information on the system drive is not automatically transferred to the new process when the number of lpenvironment partitions in the CreateProcess function is not empty. An application must manually pass information about the current folder to a 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 folder 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 folder is the default current folder of the new process on drive X.


The handle returned by the CreateProcess function has the allow permission for the process object process_all_access.

The current folder of the sub-process object in the current folder specified by the number of lpcurrentdirectory partitions. The second project specified by the number of lpcommandline partitions is the current folder of the parent process.

For Windows NT, when a process is created with create_new_process_group specified, a call to setconsolectrlhandler (null, true) is used in the new process, this means that Ctrl + C is invalid for the new process. This allows upper-level surgical programs to process Ctrl + C information themselves and selectively transmit these signals to sub-processes. CTRL + break is still valid and can be used to interrupt the running of the Process/process tree.

Refer
Allocconsole, closehandle, handler, createthread, exitprocess, exitthread, response, getcommandline, response, getexitcodeprocess, response, getstartupinfo, getsystemdirectory, getwindowsdirectory, loadmodule, OpenProcess, process_information, response, seterrormode, startupinfo, terminateprocess, waitforinputidle, waitfordebugevent, winexec

Quick info:
Import to database: kernel32.lib
Header file: WINBASE. h

CreateProcess Function Description

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.