Windows Win32 API Processthreadsapi
Windows Win32 API Processthreadsapi
Provides information about a newly created process and its primary thread.
processthreadsapi.h
Enumerations
PROCESS_MEMORY_EXHAUSTION_TYPE
QUEUE_USER_APC_FLAGS
THREAD_INFORMATION_CLASS
Functions
CreateProcessA
Creates a new process and its primary thread. The new process runs in the security context of the
calling process. (ANSI)
CreateProcessAsUserA
Creates a new process and its primary thread. The new process runs in the security context of the
user represented by the specified token. (ANSI)
CreateProcessAsUserW
Creates a new process and its primary thread. The new process runs in the security context of the
user represented by the specified token. (Unicode)
CreateProcessW
Creates a new process and its primary thread. The new process runs in the security context of the
calling process. (Unicode)
CreateRemoteThread
Creates a thread that runs in the virtual address space of another process.
CreateRemoteThreadEx
Creates a thread that runs in the virtual address space of another process and optionally specifies
extended attributes such as processor group affinity.
CreateThread
Creates a thread to execute within the virtual address space of the calling process.
DeleteProcThreadAttributeList
Deletes the specified list of attributes for process and thread creation.
ExitProcess
ExitThread
FlushProcessWriteBuffers
Flushes the write queue of each processor that is running a thread of the current process.
GetCurrentProcess
GetCurrentProcessId
GetCurrentProcessorNumber
Retrieves the number of the processor the current thread was running on during the call to this
function.
GetCurrentProcessorNumberEx
Retrieves the processor group and number of the logical processor in which the calling thread is
running.
GetCurrentThread
GetCurrentThreadId
GetCurrentThreadStackLimits
Retrieves the boundaries of the stack that was allocated by the system for the current thread.
GetExitCodeProcess
GetExitCodeThread
GetPriorityClass
Retrieves the priority class for the specified process. This value, together with the priority value of
each thread of the process, determines each thread's base priority level.
GetProcessHandleCount
Retrieves the number of open handles that belong to the specified process.
GetProcessId
GetProcessIdOfThread
Retrieves the process identifier of the process associated with the specified thread.
GetProcessInformation
GetProcessMitigationPolicy
GetProcessShutdownParameters
GetProcessTimes
GetProcessVersion
Retrieves the major and minor version numbers of the system on which the specified process
expects to run.
GetStartupInfoW
Retrieves the contents of the STARTUPINFO structure that was specified when the calling process
was created.
GetThreadDescription
GetThreadId
GetThreadIdealProcessorEx
Retrieves the processor number of the ideal processor for the specified thread.
GetThreadInformation
GetThreadIOPendingFlag
GetThreadPriority
Retrieves the priority value for the specified thread. This value, together with the priority class of
the thread's process, determines the thread's base-priority level.
GetThreadPriorityBoost
GetThreadTimes
InitializeProcThreadAttributeList
Initializes the specified list of attributes for process and thread creation.
IsProcessCritical
OpenProcess
OpenThread
QueryProcessAffinityUpdateMode
QueryProtectedPolicy
QueueUserAPC
Adds a user-mode asynchronous procedure call (APC) object to the APC queue of the specified
thread. (QueueUserAPC)
QueueUserAPC2
Adds a user-mode asynchronous procedure call (APC) object to the APC queue of the specified
thread. (QueueUserAPC2)
ResumeThread
Decrements a thread's suspend count. When the suspend count is decremented to zero, the
execution of the thread is resumed.
SetPriorityClass
Sets the priority class for the specified process. This value together with the priority value of each
thread of the process determines each thread's base priority level.
SetProcessAffinityUpdateMode
SetProcessDynamicEnforcedCetCompatibleRanges
SetProcessInformation
SetProcessMitigationPolicy
Sets a mitigation policy for the calling process. Mitigation policies enable a process to harden
itself against various types of attacks.
SetProcessPriorityBoost
Disables or enables the ability of the system to temporarily boost the priority of the threads of the
specified process.
SetProcessShutdownParameters
Sets shutdown parameters for the currently calling process. This function sets a shutdown order
for a process relative to the other processes in the system.
SetProtectedPolicy
SetThreadDescription
SetThreadIdealProcessor
Sets a preferred processor for a thread. The system schedules threads on their preferred
processors whenever possible.
SetThreadIdealProcessorEx
Sets the ideal processor for the specified thread and optionally retrieves the previous ideal
processor.
SetThreadInformation
SetThreadPriorityBoost
Disables or enables the ability of the system to temporarily boost the priority of a thread.
SetThreadStackGuarantee
Sets the minimum size of the stack associated with the calling thread or fiber that will be available
during any stack overflow exceptions.
SuspendThread
SwitchToThread
Causes the calling thread to yield execution to another thread that is ready to run on the current
processor. The operating system selects the next thread to be executed.
TerminateProcess
TerminateThread
Terminates a thread.
TlsAlloc
Allocates a thread local storage (TLS) index. Any thread of the process can subsequently use this
index to store and retrieve values that are local to the thread, because each thread receives its
own slot for the index.
TlsFree
Releases a thread local storage (TLS) index, making it available for reuse.
TlsGetValue
Retrieves the value in the calling thread's thread local storage (TLS) slot for the specified TLS
index. Each thread of a process has its own slot for each TLS index.
TlsSetValue
Stores a value in the calling thread's thread local storage (TLS) slot for the specified TLS index.
Each thread of a process has its own slot for each TLS index.
UpdateProcThreadAttribute
Updates the specified attribute in a list of attributes for process and thread creation.
Structures
APP_MEMORY_INFORMATION
Represents app memory usage at a single point in time. This structure is used by the
PROCESS_INFORMATION_CLASS class.
MEMORY_PRIORITY_INFORMATION
PROCESS_INFORMATION
Contains information about a newly created process and its primary thread. It is used with the
CreateProcess, CreateProcessAsUser, CreateProcessWithLogonW, or CreateProcessWithTokenW
function.
PROCESS_LEAP_SECOND_INFO
PROCESS_MEMORY_EXHAUSTION_INFO
PROCESS_POWER_THROTTLING_STATE
Specifies the throttling policies and how to apply them to a target process when that process is
subject to power management.
PROCESS_PROTECTION_LEVEL_INFORMATION
STARTUPINFOA
Specifies the window station, desktop, standard handles, and appearance of the main window for
a process at creation time. (ANSI)
STARTUPINFOW
Specifies the window station, desktop, standard handles, and appearance of the main window for
a process at creation time. (Unicode)
THREAD_POWER_THROTTLING_STATE
Specifies the throttling policies and how to apply them to a target thread when that thread is
subject to power management.
Feedback
Was this page helpful? ツ Yes ト No
Functions
CreateProcessA
Creates a new process and its primary thread. The new process runs in the security context of the
calling process. (ANSI)
CreateProcessAsUserA
Creates a new process and its primary thread. The new process runs in the security context of the
user represented by the specified token. (ANSI)
CreateProcessAsUserW
Creates a new process and its primary thread. The new process runs in the security context of the
user represented by the specified token. (Unicode)
CreateProcessW
Creates a new process and its primary thread. The new process runs in the security context of the
calling process. (Unicode)
CreateRemoteThread
Creates a thread that runs in the virtual address space of another process.
CreateRemoteThreadEx
Creates a thread that runs in the virtual address space of another process and optionally specifies
extended attributes such as processor group affinity.
CreateThread
Creates a thread to execute within the virtual address space of the calling process.
DeleteProcThreadAttributeList
Deletes the specified list of attributes for process and thread creation.
ExitProcess
ExitThread
FlushInstructionCache
FlushProcessWriteBuffers
Flushes the write queue of each processor that is running a thread of the current process.
GetCurrentProcess
GetCurrentProcessId
GetCurrentProcessorNumber
Retrieves the number of the processor the current thread was running on during the call to this
function.
GetCurrentProcessorNumberEx
Retrieves the processor group and number of the logical processor in which the calling thread is
running.
GetCurrentProcessToken
Retrieves a pseudo-handle that you can use as a shorthand way to refer to the access token
associated with a process.
GetCurrentThread
GetCurrentThreadEffectiveToken
Retrieves a pseudo-handle that you can use as a shorthand way to refer to the token that is
currently in effect for the thread, which is the thread token if one exists and the process token
otherwise.
GetCurrentThreadId
GetCurrentThreadStackLimits
Retrieves the boundaries of the stack that was allocated by the system for the current thread.
GetCurrentThreadToken
Retrieves a pseudo-handle that you can use as a shorthand way to refer to the impersonation
token that was assigned to the current thread.
GetExitCodeProcess
GetExitCodeThread
GetMachineTypeAttributes
Queries if the specified architecture is supported on the current system, either natively or by any
form of compatibility or emulation layer.
GetPriorityClass
Retrieves the priority class for the specified process. This value, together with the priority value of
each thread of the process, determines each thread's base priority level.
GetProcessDefaultCpuSetMasks
Retrieves the list of CPU Sets in the process default set that was set by
SetProcessDefaultCpuSetMasks or SetProcessDefaultCpuSets.
GetProcessDefaultCpuSets
Retrieves the list of CPU Sets in the process default set that was set by SetProcessDefaultCpuSets.
GetProcessHandleCount
Retrieves the number of open handles that belong to the specified process.
GetProcessId
GetProcessIdOfThread
Retrieves the process identifier of the process associated with the specified thread.
GetProcessInformation
GetProcessMitigationPolicy
GetProcessPriorityBoost
GetProcessShutdownParameters
GetProcessTimes
GetProcessVersion
Retrieves the major and minor version numbers of the system on which the specified process
expects to run.
GetStartupInfoW
Retrieves the contents of the STARTUPINFO structure that was specified when the calling process
was created.
GetSystemCpuSetInformation
Allows an application to query the available CPU Sets on the system, and their current state.
GetSystemTimes
Retrieves system timing information. On a multiprocessor system, the values returned are the sum
of the designated times across all processors.
GetThreadContext
GetThreadDescription
GetThreadId
GetThreadIdealProcessorEx
Retrieves the processor number of the ideal processor for the specified thread.
GetThreadInformation
GetThreadIOPendingFlag
GetThreadPriority
Retrieves the priority value for the specified thread. This value, together with the priority class of
the thread's process, determines the thread's base-priority level.
GetThreadPriorityBoost
GetThreadSelectedCpuSetMasks
Returns the explicit CPU Set assignment of the specified thread, if any assignment was set using
SetThreadSelectedCpuSetMasks or SetThreadSelectedCpuSets.
GetThreadSelectedCpuSets
Returns the explicit CPU Set assignment of the specified thread, if any assignment was set using
the SetThreadSelectedCpuSets API.
GetThreadTimes
InitializeProcThreadAttributeList
Initializes the specified list of attributes for process and thread creation.
IsProcessCritical
IsProcessorFeaturePresent
Determines whether the specified processor feature is supported by the current computer.
OpenProcess
OpenProcessToken
OpenThread
OpenThreadToken
ProcessIdToSessionId
Retrieves the Remote Desktop Services session associated with a specified process.
QueryProcessAffinityUpdateMode
QueryProtectedPolicy
QueueUserAPC
Adds a user-mode asynchronous procedure call (APC) object to the APC queue of the specified
thread. (QueueUserAPC)
QueueUserAPC2
Adds a user-mode asynchronous procedure call (APC) object to the APC queue of the specified
thread. (QueueUserAPC2)
ResumeThread
Decrements a thread's suspend count. When the suspend count is decremented to zero, the
execution of the thread is resumed.
SetPriorityClass
Sets the priority class for the specified process. This value together with the priority value of each
thread of the process determines each thread's base priority level.
SetProcessAffinityUpdateMode
SetProcessDefaultCpuSetMasks
SetProcessDefaultCpuSets
SetProcessDynamicEHContinuationTargets
Sets dynamic exception handling continuation targets for the specified process.
SetProcessDynamicEnforcedCetCompatibleRanges
SetProcessInformation
SetProcessMitigationPolicy
Sets a mitigation policy for the calling process. Mitigation policies enable a process to harden
itself against various types of attacks.
SetProcessPriorityBoost
Disables or enables the ability of the system to temporarily boost the priority of the threads of the
specified process.
SetProcessShutdownParameters
Sets shutdown parameters for the currently calling process. This function sets a shutdown order
for a process relative to the other processes in the system.
SetProtectedPolicy
SetThreadContext
SetThreadDescription
SetThreadIdealProcessor
Sets a preferred processor for a thread. The system schedules threads on their preferred
processors whenever possible.
SetThreadIdealProcessorEx
Sets the ideal processor for the specified thread and optionally retrieves the previous ideal
processor.
SetThreadInformation
SetThreadPriority
Sets the priority value for the specified thread. This value, together with the priority class of the
thread's process, determines the thread's base priority level.
SetThreadPriorityBoost
Disables or enables the ability of the system to temporarily boost the priority of a thread.
SetThreadSelectedCpuSetMasks
Sets the selected CPU Sets assignment for the specified thread. This assignment overrides the
process default assignment, if one is set. (SetThreadSelectedCpuSetMasks)
SetThreadSelectedCpuSets
Sets the selected CPU Sets assignment for the specified thread. This assignment overrides the
process default assignment, if one is set. (SetThreadSelectedCpuSets)
SetThreadStackGuarantee
Sets the minimum size of the stack associated with the calling thread or fiber that will be available
during any stack overflow exceptions.
SetThreadToken
Assigns an impersonation token to a thread. The function can also cause a thread to stop using an
impersonation token.
SuspendThread
SwitchToThread
Causes the calling thread to yield execution to another thread that is ready to run on the current
processor. The operating system selects the next thread to be executed.
TerminateProcess
TerminateThread
Terminates a thread.
TlsAlloc
Allocates a thread local storage (TLS) index. Any thread of the process can subsequently use this
index to store and retrieve values that are local to the thread, because each thread receives its
own slot for the index.
TlsFree
Releases a thread local storage (TLS) index, making it available for reuse.
TlsGetValue
Retrieves the value in the calling thread's thread local storage (TLS) slot for the specified TLS
index. Each thread of a process has its own slot for each TLS index.
TlsSetValue
Stores a value in the calling thread's thread local storage (TLS) slot for the specified TLS index.
Each thread of a process has its own slot for each TLS index.
UpdateProcThreadAttribute
Updates the specified attribute in a list of attributes for process and thread creation.
Structures
APP_MEMORY_INFORMATION
Represents app memory usage at a single point in time. This structure is used by the
PROCESS_INFORMATION_CLASS class.
MEMORY_PRIORITY_INFORMATION
PROCESS_INFORMATION
Contains information about a newly created process and its primary thread. It is used with the
CreateProcess, CreateProcessAsUser, CreateProcessWithLogonW, or CreateProcessWithTokenW
function.
PROCESS_LEAP_SECOND_INFO
PROCESS_MACHINE_INFORMATION
Specifies the architecture of a process and if that architecture of code can run in user mode,
kernel mode, and/or under WoW64 on the host operating system.
PROCESS_MEMORY_EXHAUSTION_INFO
PROCESS_POWER_THROTTLING_STATE
Specifies the throttling policies and how to apply them to a target process when that process is
subject to power management.
PROCESS_PROTECTION_LEVEL_INFORMATION
STARTUPINFOA
Specifies the window station, desktop, standard handles, and appearance of the main window for
a process at creation time. (ANSI)
STARTUPINFOW
Specifies the window station, desktop, standard handles, and appearance of the main window for
a process at creation time. (Unicode)
THREAD_POWER_THROTTLING_STATE
Specifies the throttling policies and how to apply them to a target thread when that thread is
subject to power management.
Enumerations
MACHINE_ATTRIBUTES
Specifies the ways in which an architecture of code can run on a host operating system. More than
one bit may be set.
PROCESS_INFORMATION_CLASS
PROCESS_MEMORY_EXHAUSTION_TYPE
QUEUE_USER_APC_FLAGS
THREAD_INFORMATION_CLASS
Represents app memory usage at a single point in time. This structure is used by the
PROCESS_INFORMATION_CLASS enumeration.
Syntax
C++
Members
AvailableCommit
PrivateCommitUsage
PeakPrivateCommitUsage
TotalCommitUsage
Requirements
Minimum supported client Windows 10, version 1511 [desktop apps | UWP apps]
Minimum supported server Windows Server 2016 [desktop apps | UWP apps]
See also
PROCESS_INFORMATION_CLASS enumeration
Feedback
Was this page helpful? ツ Yes ト No
Creates a new process and its primary thread. The new process runs in the security
context of the calling process.
If the calling process is impersonating another user, the new process uses the token for
the calling process, not the impersonation token. To run the new process in the security
context of the user represented by the impersonation token, use the
CreateProcessAsUser or CreateProcessWithLogonW function.
Syntax
C++
BOOL CreateProcessA(
[in, optional] LPCSTR lpApplicationName,
[in, out, optional] LPSTR lpCommandLine,
[in, optional] LPSECURITY_ATTRIBUTES lpProcessAttributes,
[in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes,
[in] BOOL bInheritHandles,
[in] DWORD dwCreationFlags,
[in, optional] LPVOID lpEnvironment,
[in, optional] LPCSTR lpCurrentDirectory,
[in] LPSTARTUPINFOA lpStartupInfo,
[out] LPPROCESS_INFORMATION lpProcessInformation
);
Parameters
[in, optional] lpApplicationName
The string can specify the full path and file name of the module to execute or it can
specify a partial name. In the case of a partial name, the function uses the current drive
and current directory to complete the specification. The function will not use the search
path. This parameter must include the file name extension; no default extension is
assumed.
The lpApplicationName parameter can be NULL. In that case, the module name must be
the first white space–delimited token in the lpCommandLine string. If you are using a
long file name that contains a space, use quoted strings to indicate where the file name
ends and the arguments begin; otherwise, the file name is ambiguous. For example,
consider the string "c:\program files\sub dir\program name". This string can be
interpreted in a number of ways. The system tries to interpret the possibilities in the
following order:
1. c:\program.exe
2. c:\program files\sub.exe
3. c:\program files\sub dir\program.exe
4. c:\program files\sub dir\program name.exe
To run a batch file, you must start the command interpreter; set lpApplicationName to
cmd.exe and set lpCommandLine to the following arguments: /c plus the name of the
batch file.
The maximum length of this string is 32,767 characters, including the Unicode
terminating null character. If lpApplicationName is NULL, the module name portion of
lpCommandLine is limited to MAX_PATH characters.
The Unicode version of this function, CreateProcessW, can modify the contents of this
string. Therefore, this parameter cannot be a pointer to read-only memory (such as a
const variable or a literal string). If this parameter is a constant string, the function may
cause an access violation.
The lpCommandLine parameter can be NULL. In that case, the function uses the string
pointed to by lpApplicationName as the command line.
The system adds a terminating null character to the command-line string to separate
the file name from the arguments. This divides the original string into two strings for
internal processing.
The lpSecurityDescriptor member of the structure specifies a security descriptor for the
new process. If lpProcessAttributes is NULL or lpSecurityDescriptor is NULL, the process
gets a default security descriptor. The ACLs in the default security descriptor for a
process come from the primary token of the creator.Windows XP: The ACLs in the
default security descriptor for a process come from the primary or impersonation token
of the creator. This behavior changed with Windows XP with SP2 and Windows
Server 2003.
The lpSecurityDescriptor member of the structure specifies a security descriptor for the
main thread. If lpThreadAttributes is NULL or lpSecurityDescriptor is NULL, the thread
gets a default security descriptor. The ACLs in the default security descriptor for a thread
come from the process token.Windows XP: The ACLs in the default security descriptor
for a thread come from the primary or impersonation token of the creator. This behavior
changed with Windows XP with SP2 and Windows Server 2003.
[in] bInheritHandles
If this parameter is TRUE, each inheritable handle in the calling process is inherited by
the new process. If the parameter is FALSE, the handles are not inherited. Note that
inherited handles have the same value and access rights as the original handles. For
additional discussion of inheritable handles, see Remarks.
Terminal Services: You cannot inherit handles across sessions. Additionally, if this
parameter is TRUE, you must create the process in the same session as the caller.
Protected Process Light (PPL) processes: The generic handle inheritance is blocked
when a PPL process creates a non-PPL process since PROCESS_DUP_HANDLE is not
allowed from a non-PPL process to a PPL process. See Process Security and Access
Rights
[in] dwCreationFlags
The flags that control the priority class and the creation of the process. For a list of
values, see Process Creation Flags.
This parameter also controls the new process's priority class, which is used to determine
the scheduling priorities of the process's threads. For a list of values, see
GetPriorityClass. If none of the priority class flags is specified, the priority class defaults
to NORMAL_PRIORITY_CLASS unless the priority class of the creating process is
IDLE_PRIORITY_CLASS or BELOW_NORMAL_PRIORITY_CLASS. In this case, the child
process receives the default priority class of the calling process.
The process inherits both the error mode of the caller and the parent's console.
The environment block for the new process is assumed to contain ANSI characters
(see lpEnvironment parameter for additional information).
A 16-bit Windows-based application runs in a shared Virtual DOS machine (VDM).
[in, optional] lpEnvironment
A pointer to the environment block for the new process. If this parameter is NULL, the
new process uses the environment of the calling process.
name=value\0
Because the equal sign is used as a separator, it must not be used in the name of an
environment variable.
An environment block can contain either Unicode or ANSI characters. If the environment
block pointed to by lpEnvironment contains Unicode characters, be sure that
dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT.
The ANSI version of this function, CreateProcessA fails if the total size of the
environment block for the process exceeds 32,767 characters.
Note that an ANSI environment block is terminated by two zero bytes: one for the last
string, one more to terminate the block. A Unicode environment block is terminated by
four zero bytes: two for the last string, two more to terminate the block.
The full path to the current directory for the process. The string can also specify a UNC
path.
If this parameter is NULL, the new process will have the same current drive and directory
as the calling process. (This feature is provided primarily for shells that need to start an
application and specify its initial drive and working directory.)
[in] lpStartupInfo
Important The caller is responsible for ensuring that the standard handle fields in
STARTUPINFO contain valid handle values. These fields are copied unchanged to
the child process without validation, even when the dwFlags member specifies
STARTF_USESTDHANDLES. Incorrect values can cause the child process to
misbehave or crash. Use the Application Verifier runtime verification tool to detect
invalid handles.
[out] lpProcessInformation
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Note that the function returns before the process has finished initialization. If a required
DLL cannot be located or fails to initialize, the process is terminated. To get the
termination status of a process, call GetExitCodeProcess.
Remarks
The process is assigned a process identifier. The identifier is valid until the process
terminates. It can be used to identify the process, or specified in the OpenProcess
function to open a handle to the process. The initial thread in the process is also
assigned a thread identifier. It can be specified in the OpenThread function to open a
handle to the thread. The identifier is valid until the thread terminates and can be used
to uniquely identify the thread within the system. These identifiers are returned in the
PROCESS_INFORMATION structure.
The name of the executable in the command line that the operating system provides to
a process is not necessarily identical to that in the command line that the calling process
gives to the CreateProcess function. The operating system may prepend a fully qualified
path to an executable name that is provided without a fully qualified path.
The calling thread can use the WaitForInputIdle function to wait until the new process
has finished its initialization and is waiting for user input with no input pending. This can
be useful for synchronization between parent and child processes, because
CreateProcess returns without waiting for the new process to finish its initialization. For
example, the creating process would use WaitForInputIdle before trying to find a
window associated with the new process.
The preferred way to shut down a process is by using the ExitProcess function, because
this function sends notification of approaching termination to all DLLs attached to the
process. Other means of shutting down a process do not notify the attached DLLs. Note
that when a thread calls ExitProcess, other threads of the process are terminated
without an opportunity to execute any additional code (including the thread termination
code of attached DLLs). For more information, see Terminating a Process.
A parent process can directly alter the environment variables of a child process during
process creation. This is the only situation when a process can directly change the
environment settings of another process. For more information, see Changing
Environment Variables.
One way to obtain the current directory information for a drive X is to make the
following call: GetFullPathName("X:", ...) . That avoids an application having to scan
the environment block. If the full path returned is X:, there is no need to pass that value
on as environment data, since the root directory is the default current directory for drive
X of a new process.
By default, passing TRUE as the value of the bInheritHandles parameter causes all
inheritable handles to be inherited by the new process. This can be problematic for
applications which create processes from multiple threads simultaneously yet desire
each process to inherit different handles. Applications can use the
UpdateProcThreadAttributeList function with the
PROC_THREAD_ATTRIBUTE_HANDLE_LIST parameter to provide a list of handles to be
inherited by a particular process.
Security Remarks
The first parameter, lpApplicationName, can be NULL, in which case the executable
name must be in the white space–delimited string pointed to by lpCommandLine. If the
executable or path name has a space in it, there is a risk that a different executable
could be run because of the way the function parses spaces. The following example is
dangerous because the function will attempt to run "Program.exe", if it exists, instead of
"MyApp.exe".
syntax
To avoid this problem, do not pass NULL for lpApplicationName. If you do pass NULL for
lpApplicationName, use quotation marks around the executable path in lpCommandLine,
as shown in the example below.
syntax
Examples
7 Note
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
CloseHandle
ShellExecuteA
CreateProcessAsUser
CreateProcessWithLogonW
ExitProcess
GetCommandLine
GetEnvironmentStrings
GetExitCodeProcess
GetFullPathName
GetStartupInfo
OpenProcess
PROCESS_INFORMATION
Processes
SECURITY_ATTRIBUTES
STARTUPINFO
STARTUPINFOEX
SetErrorMode
TerminateProcess
WaitForInputIdle
Feedback
Was this page helpful? ツ Yes ト No
Creates a new process and its primary thread. The new process runs in the security
context of the user represented by the specified token.
Typically, the process that calls the CreateProcessAsUser function must have the
SE_INCREASE_QUOTA_NAME privilege and may require the
SE_ASSIGNPRIMARYTOKEN_NAME privilege if the token is not assignable. If this
function fails with ERROR_PRIVILEGE_NOT_HELD (1314), use the
CreateProcessWithLogonW function instead. CreateProcessWithLogonW requires no
special privileges, but the specified user account must be allowed to log on interactively.
Generally, it is best to use CreateProcessWithLogonW to create a process with alternate
credentials.
Syntax
C++
BOOL CreateProcessAsUserA(
[in, optional] HANDLE hToken,
[in, optional] LPCSTR lpApplicationName,
[in, out, optional] LPSTR lpCommandLine,
[in, optional] LPSECURITY_ATTRIBUTES lpProcessAttributes,
[in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes,
[in] BOOL bInheritHandles,
[in] DWORD dwCreationFlags,
[in, optional] LPVOID lpEnvironment,
[in, optional] LPCSTR lpCurrentDirectory,
[in] LPSTARTUPINFOA lpStartupInfo,
[out] LPPROCESS_INFORMATION lpProcessInformation
);
Parameters
[in, optional] hToken
A handle to the primary token that represents a user. The handle must have the
TOKEN_QUERY, TOKEN_DUPLICATE, and TOKEN_ASSIGN_PRIMARY access rights. For
more information, see Access Rights for Access-Token Objects. The user represented by
the token must have read and execute access to the application specified by the
lpApplicationName or the lpCommandLine parameter.
To get a primary token that represents the specified user, call the LogonUser function.
Alternatively, you can call the DuplicateTokenEx function to convert an impersonation
token into a primary token. This allows a server application that is impersonating a client
to create a process that has the security context of the client.
Terminal Services: The process is run in the session specified in the token. By default,
this is the same session that called LogonUser. To change the session, use the
SetTokenInformation function.
The string can specify the full path and file name of the module to execute or it can
specify a partial name. In the case of a partial name, the function uses the current drive
and current directory to complete the specification. The function will not use the search
path. This parameter must include the file name extension; no default extension is
assumed.
The lpApplicationName parameter can be NULL. In that case, the module name must be
the first white space–delimited token in the lpCommandLine string. If you are using a
long file name that contains a space, use quoted strings to indicate where the file name
ends and the arguments begin; otherwise, the file name is ambiguous. For example,
consider the string "c:\program files\sub dir\program name". This string can be
interpreted in a number of ways. The system tries to interpret the possibilities in the
following order:
The command line to be executed. The maximum length of this string is 32K characters.
If lpApplicationName is NULL, the module name portion of lpCommandLine is limited to
MAX_PATH characters.
The Unicode version of this function, CreateProcessAsUserW, can modify the contents
of this string. Therefore, this parameter cannot be a pointer to read-only memory (such
as a const variable or a literal string). If this parameter is a constant string, the function
may cause an access violation.
The lpCommandLine parameter can be NULL. In that case, the function uses the string
pointed to by lpApplicationName as the command line.
[in] bInheritHandles
If this parameter is TRUE, each inheritable handle in the calling process is inherited by
the new process. If the parameter is FALSE, the handles are not inherited. Note that
inherited handles have the same value and access rights as the original handles. For
additional discussion of inheritable handles, see Remarks.
Terminal Services: You cannot inherit handles across sessions. Additionally, if this
parameter is TRUE, you must create the process in the same session as the caller.
Protected Process Light (PPL) processes: The generic handle inheritance is blocked
when a PPL process creates a non-PPL process since PROCESS_DUP_HANDLE is not
allowed from a non-PPL process to a PPL process. See Process Security and Access
Rights
[in] dwCreationFlags
The flags that control the priority class and the creation of the process. For a list of
values, see Process Creation Flags.
This parameter also controls the new process's priority class, which is used to determine
the scheduling priorities of the process's threads. For a list of values, see
GetPriorityClass. If none of the priority class flags is specified, the priority class defaults
to NORMAL_PRIORITY_CLASS unless the priority class of the creating process is
IDLE_PRIORITY_CLASS or BELOW_NORMAL_PRIORITY_CLASS. In this case, the child
process receives the default priority class of the calling process.
The process inherits both the error mode of the caller and the parent's console.
The environment block for the new process is assumed to contain ANSI characters
(see lpEnvironment parameter for additional information).
A 16-bit Windows-based application runs in a shared Virtual DOS machine (VDM).
A pointer to an environment block for the new process. If this parameter is NULL, the
new process uses the environment of the calling process.
name=value\0
Because the equal sign is used as a separator, it must not be used in the name of an
environment variable.
An environment block can contain either Unicode or ANSI characters. If the environment
block pointed to by lpEnvironment contains Unicode characters, be sure that
dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT.
The ANSI version of this function, CreateProcessAsUserA fails if the total size of the
environment block for the process exceeds 32,767 characters.
Note that an ANSI environment block is terminated by two zero bytes: one for the last
string, one more to terminate the block. A Unicode environment block is terminated by
four zero bytes: two for the last string, two more to terminate the block.
Windows Server 2003 and Windows XP: If the size of the combined user and system
environment variable exceeds 8192 bytes, the process created by CreateProcessAsUser
no longer runs with the environment block passed to the function by the parent
process. Instead, the child process runs with the environment block returned by the
CreateEnvironmentBlock function.
To retrieve a copy of the environment block for a given user, use the
CreateEnvironmentBlock function.
The full path to the current directory for the process. The string can also specify a UNC
path.
If this parameter is NULL, the new process will have the same current drive and directory
as the calling process. (This feature is provided primarily for shells that need to start an
application and specify its initial drive and working directory.)
[in] lpStartupInfo
The user must have full access to both the specified window station and desktop. If you
want the process to be interactive, specify winsta0\default. If the lpDesktop member is
NULL, the new process inherits the desktop and window station of its parent process. If
this member is an empty string, "", the new process connects to a window station using
the rules described in Process Connection to a Window Station.
Important The caller is responsible for ensuring that the standard handle fields in
STARTUPINFO contain valid handle values. These fields are copied unchanged to
the child process without validation, even when the dwFlags member specifies
STARTF_USESTDHANDLES. Incorrect values can cause the child process to
misbehave or crash. Use the Application Verifier runtime verification tool to detect
invalid handles.
[out] lpProcessInformation
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Note that the function returns before the process has finished initialization. If a required
DLL cannot be located or fails to initialize, the process is terminated. To get the
termination status of a process, call GetExitCodeProcess.
Remarks
CreateProcessAsUser must be able to open the primary token of the calling process
with the TOKEN_DUPLICATE and TOKEN_IMPERSONATE access rights.
CreateProcessAsUser does not load the specified user's profile into the HKEY_USERS
registry key. Therefore, to access the information in the HKEY_CURRENT_USER registry
key, you must load the user's profile information into HKEY_USERS with the
LoadUserProfile function before calling CreateProcessAsUser. Be sure to call
UnloadUserProfile after the new process exits.
If the lpEnvironment parameter is NULL, the new process inherits the environment of the
calling process. CreateProcessAsUser does not automatically modify the environment
block to include environment variables specific to the user represented by hToken. For
example, the USERNAME and USERDOMAIN variables are inherited from the calling
process if lpEnvironment is NULL. It is your responsibility to prepare the environment
block for the new process and specify it in lpEnvironment.
The process is assigned a process identifier. The identifier is valid until the process
terminates. It can be used to identify the process, or specified in the OpenProcess
function to open a handle to the process. The initial thread in the process is also
assigned a thread identifier. It can be specified in the OpenThread function to open a
handle to the thread. The identifier is valid until the thread terminates and can be used
to uniquely identify the thread within the system. These identifiers are returned in the
PROCESS_INFORMATION structure.
The calling thread can use the WaitForInputIdle function to wait until the new process
has finished its initialization and is waiting for user input with no input pending. This can
be useful for synchronization between parent and child processes, because
CreateProcessAsUser returns without waiting for the new process to finish its
initialization. For example, the creating process would use WaitForInputIdle before
trying to find a window associated with the new process.
The preferred way to shut down a process is by using the ExitProcess function, because
this function sends notification of approaching termination to all DLLs attached to the
process. Other means of shutting down a process do not notify the attached DLLs. Note
that when a thread calls ExitProcess, other threads of the process are terminated
without an opportunity to execute any additional code (including the thread termination
code of attached DLLs). For more information, see Terminating a Process.
By default, passing TRUE as the value of the bInheritHandles parameter causes all
inheritable handles to be inherited by the new process. This can be problematic for
applications which create processes from multiple threads simultaneously yet desire
each process to inherit different handles. Applications can use the
UpdateProcThreadAttributeList function with the
PROC_THREAD_ATTRIBUTE_HANDLE_LIST parameter to provide a list of handles to be
inherited by a particular process.
Security Remarks
The lpApplicationName parameter can be NULL, in which case the executable name
must be the first white space–delimited string in lpCommandLine. If the executable or
path name has a space in it, there is a risk that a different executable could be run
because of the way the function parses spaces. The following example is dangerous
because the function will attempt to run "Program.exe", if it exists, instead of
"MyApp.exe".
syntax
To avoid this problem, do not pass NULL for lpApplicationName. If you do pass NULL for
lpApplicationName, use quotation marks around the executable path in lpCommandLine,
as shown in the example below.
syntax
Examples
For an example, see Starting an Interactive Client Process.
7 Note
Requirements
Library Advapi32.lib
DLL Advapi32.dll
See also
CloseHandle
CreateEnvironmentBlock
CreateProcess
CreateProcessWithLogonW
ExitProcess
GetEnvironmentStrings
GetExitCodeProcess
GetStartupInfo
ImpersonateLoggedOnUser
LoadUserProfile
PROCESS_INFORMATION
Processes
SECURITY_ATTRIBUTES
SHCreateProcessAsUserW
STARTUPINFO
STARTUPINFOEX
SetErrorMode
WaitForInputIdle
Feedback
Was this page helpful? ツ Yes ト No
Creates a new process and its primary thread. The new process runs in the security
context of the user represented by the specified token.
Typically, the process that calls the CreateProcessAsUser function must have the
SE_INCREASE_QUOTA_NAME privilege and may require the
SE_ASSIGNPRIMARYTOKEN_NAME privilege if the token is not assignable. If this
function fails with ERROR_PRIVILEGE_NOT_HELD (1314), use the
CreateProcessWithLogonW function instead. CreateProcessWithLogonW requires no
special privileges, but the specified user account must be allowed to log on interactively.
Generally, it is best to use CreateProcessWithLogonW to create a process with alternate
credentials.
Syntax
C++
BOOL CreateProcessAsUserW(
[in, optional] HANDLE hToken,
[in, optional] LPCWSTR lpApplicationName,
[in, out, optional] LPWSTR lpCommandLine,
[in, optional] LPSECURITY_ATTRIBUTES lpProcessAttributes,
[in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes,
[in] BOOL bInheritHandles,
[in] DWORD dwCreationFlags,
[in, optional] LPVOID lpEnvironment,
[in, optional] LPCWSTR lpCurrentDirectory,
[in] LPSTARTUPINFOW lpStartupInfo,
[out] LPPROCESS_INFORMATION lpProcessInformation
);
Parameters
[in, optional] hToken
A handle to the primary token that represents a user. The handle must have the
TOKEN_QUERY, TOKEN_DUPLICATE, and TOKEN_ASSIGN_PRIMARY access rights. For
more information, see Access Rights for Access-Token Objects. The user represented by
the token must have read and execute access to the application specified by the
lpApplicationName or the lpCommandLine parameter.
To get a primary token that represents the specified user, call the LogonUser function.
Alternatively, you can call the DuplicateTokenEx function to convert an impersonation
token into a primary token. This allows a server application that is impersonating a client
to create a process that has the security context of the client.
Terminal Services: The process is run in the session specified in the token. By default,
this is the same session that called LogonUser. To change the session, use the
SetTokenInformation function.
The string can specify the full path and file name of the module to execute or it can
specify a partial name. In the case of a partial name, the function uses the current drive
and current directory to complete the specification. The function will not use the search
path. This parameter must include the file name extension; no default extension is
assumed.
The lpApplicationName parameter can be NULL. In that case, the module name must be
the first white space–delimited token in the lpCommandLine string. If you are using a
long file name that contains a space, use quoted strings to indicate where the file name
ends and the arguments begin; otherwise, the file name is ambiguous. For example,
consider the string "c:\program files\sub dir\program name". This string can be
interpreted in a number of ways. The system tries to interpret the possibilities in the
following order:
The command line to be executed. The maximum length of this string is 32K characters.
If lpApplicationName is NULL, the module name portion of lpCommandLine is limited to
MAX_PATH characters.
The Unicode version of this function, CreateProcessAsUserW, can modify the contents
of this string. Therefore, this parameter cannot be a pointer to read-only memory (such
as a const variable or a literal string). If this parameter is a constant string, the function
may cause an access violation.
The lpCommandLine parameter can be NULL. In that case, the function uses the string
pointed to by lpApplicationName as the command line.
[in] bInheritHandles
If this parameter is TRUE, each inheritable handle in the calling process is inherited by
the new process. If the parameter is FALSE, the handles are not inherited. Note that
inherited handles have the same value and access rights as the original handles. For
additional discussion of inheritable handles, see Remarks.
Terminal Services: You cannot inherit handles across sessions. Additionally, if this
parameter is TRUE, you must create the process in the same session as the caller.
Protected Process Light (PPL) processes: The generic handle inheritance is blocked
when a PPL process creates a non-PPL process since PROCESS_DUP_HANDLE is not
allowed from a non-PPL process to a PPL process. See Process Security and Access
Rights
[in] dwCreationFlags
The flags that control the priority class and the creation of the process. For a list of
values, see Process Creation Flags.
This parameter also controls the new process's priority class, which is used to determine
the scheduling priorities of the process's threads. For a list of values, see
GetPriorityClass. If none of the priority class flags is specified, the priority class defaults
to NORMAL_PRIORITY_CLASS unless the priority class of the creating process is
IDLE_PRIORITY_CLASS or BELOW_NORMAL_PRIORITY_CLASS. In this case, the child
process receives the default priority class of the calling process.
The process inherits both the error mode of the caller and the parent's console.
The environment block for the new process is assumed to contain ANSI characters
(see lpEnvironment parameter for additional information).
A 16-bit Windows-based application runs in a shared Virtual DOS machine (VDM).
A pointer to an environment block for the new process. If this parameter is NULL, the
new process uses the environment of the calling process.
name=value\0
Because the equal sign is used as a separator, it must not be used in the name of an
environment variable.
An environment block can contain either Unicode or ANSI characters. If the environment
block pointed to by lpEnvironment contains Unicode characters, be sure that
dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT.
The ANSI version of this function, CreateProcessAsUserA fails if the total size of the
environment block for the process exceeds 32,767 characters.
Note that an ANSI environment block is terminated by two zero bytes: one for the last
string, one more to terminate the block. A Unicode environment block is terminated by
four zero bytes: two for the last string, two more to terminate the block.
Windows Server 2003 and Windows XP: If the size of the combined user and system
environment variable exceeds 8192 bytes, the process created by CreateProcessAsUser
no longer runs with the environment block passed to the function by the parent
process. Instead, the child process runs with the environment block returned by the
CreateEnvironmentBlock function.
To retrieve a copy of the environment block for a given user, use the
CreateEnvironmentBlock function.
The full path to the current directory for the process. The string can also specify a UNC
path.
If this parameter is NULL, the new process will have the same current drive and directory
as the calling process. (This feature is provided primarily for shells that need to start an
application and specify its initial drive and working directory.)
[in] lpStartupInfo
The user must have full access to both the specified window station and desktop. If you
want the process to be interactive, specify winsta0\default. If the lpDesktop member is
NULL, the new process inherits the desktop and window station of its parent process. If
this member is an empty string, "", the new process connects to a window station using
the rules described in Process Connection to a Window Station.
Important The caller is responsible for ensuring that the standard handle fields in
STARTUPINFO contain valid handle values. These fields are copied unchanged to
the child process without validation, even when the dwFlags member specifies
STARTF_USESTDHANDLES. Incorrect values can cause the child process to
misbehave or crash. Use the Application Verifier runtime verification tool to detect
invalid handles.
[out] lpProcessInformation
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Note that the function returns before the process has finished initialization. If a required
DLL cannot be located or fails to initialize, the process is terminated. To get the
termination status of a process, call GetExitCodeProcess.
Remarks
CreateProcessAsUser must be able to open the primary token of the calling process
with the TOKEN_DUPLICATE and TOKEN_IMPERSONATE access rights.
CreateProcessAsUser does not load the specified user's profile into the HKEY_USERS
registry key. Therefore, to access the information in the HKEY_CURRENT_USER registry
key, you must load the user's profile information into HKEY_USERS with the
LoadUserProfile function before calling CreateProcessAsUser. Be sure to call
UnloadUserProfile after the new process exits.
If the lpEnvironment parameter is NULL, the new process inherits the environment of the
calling process. CreateProcessAsUser does not automatically modify the environment
block to include environment variables specific to the user represented by hToken. For
example, the USERNAME and USERDOMAIN variables are inherited from the calling
process if lpEnvironment is NULL. It is your responsibility to prepare the environment
block for the new process and specify it in lpEnvironment.
The process is assigned a process identifier. The identifier is valid until the process
terminates. It can be used to identify the process, or specified in the OpenProcess
function to open a handle to the process. The initial thread in the process is also
assigned a thread identifier. It can be specified in the OpenThread function to open a
handle to the thread. The identifier is valid until the thread terminates and can be used
to uniquely identify the thread within the system. These identifiers are returned in the
PROCESS_INFORMATION structure.
The calling thread can use the WaitForInputIdle function to wait until the new process
has finished its initialization and is waiting for user input with no input pending. This can
be useful for synchronization between parent and child processes, because
CreateProcessAsUser returns without waiting for the new process to finish its
initialization. For example, the creating process would use WaitForInputIdle before
trying to find a window associated with the new process.
The preferred way to shut down a process is by using the ExitProcess function, because
this function sends notification of approaching termination to all DLLs attached to the
process. Other means of shutting down a process do not notify the attached DLLs. Note
that when a thread calls ExitProcess, other threads of the process are terminated
without an opportunity to execute any additional code (including the thread termination
code of attached DLLs). For more information, see Terminating a Process.
By default, passing TRUE as the value of the bInheritHandles parameter causes all
inheritable handles to be inherited by the new process. This can be problematic for
applications which create processes from multiple threads simultaneously yet desire
each process to inherit different handles. Applications can use the
UpdateProcThreadAttributeList function with the
PROC_THREAD_ATTRIBUTE_HANDLE_LIST parameter to provide a list of handles to be
inherited by a particular process.
Security Remarks
The lpApplicationName parameter can be NULL, in which case the executable name
must be the first white space–delimited string in lpCommandLine. If the executable or
path name has a space in it, there is a risk that a different executable could be run
because of the way the function parses spaces. The following example is dangerous
because the function will attempt to run "Program.exe", if it exists, instead of
"MyApp.exe".
syntax
To avoid this problem, do not pass NULL for lpApplicationName. If you do pass NULL for
lpApplicationName, use quotation marks around the executable path in lpCommandLine,
as shown in the example below.
syntax
Examples
For an example, see Starting an Interactive Client Process.
7 Note
Requirements
Library Advapi32.lib
DLL Advapi32.dll
See also
CloseHandle
CreateEnvironmentBlock
CreateProcess
CreateProcessWithLogonW
ExitProcess
GetEnvironmentStrings
GetExitCodeProcess
GetStartupInfo
ImpersonateLoggedOnUser
LoadUserProfile
PROCESS_INFORMATION
Processes
SECURITY_ATTRIBUTES
SHCreateProcessAsUserW
STARTUPINFO
STARTUPINFOEX
SetErrorMode
WaitForInputIdle
Feedback
Was this page helpful? ツ Yes ト No
Creates a new process and its primary thread. The new process runs in the security
context of the calling process.
If the calling process is impersonating another user, the new process uses the token for
the calling process, not the impersonation token. To run the new process in the security
context of the user represented by the impersonation token, use the
CreateProcessAsUser or CreateProcessWithLogonW function.
Syntax
C++
BOOL CreateProcessW(
[in, optional] LPCWSTR lpApplicationName,
[in, out, optional] LPWSTR lpCommandLine,
[in, optional] LPSECURITY_ATTRIBUTES lpProcessAttributes,
[in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes,
[in] BOOL bInheritHandles,
[in] DWORD dwCreationFlags,
[in, optional] LPVOID lpEnvironment,
[in, optional] LPCWSTR lpCurrentDirectory,
[in] LPSTARTUPINFOW lpStartupInfo,
[out] LPPROCESS_INFORMATION lpProcessInformation
);
Parameters
[in, optional] lpApplicationName
The string can specify the full path and file name of the module to execute or it can
specify a partial name. In the case of a partial name, the function uses the current drive
and current directory to complete the specification. The function will not use the search
path. This parameter must include the file name extension; no default extension is
assumed.
The lpApplicationName parameter can be NULL. In that case, the module name must be
the first white space–delimited token in the lpCommandLine string. If you are using a
long file name that contains a space, use quoted strings to indicate where the file name
ends and the arguments begin; otherwise, the file name is ambiguous. For example,
consider the string "c:\program files\sub dir\program name". This string can be
interpreted in a number of ways. The system tries to interpret the possibilities in the
following order:
1. c:\program.exe
2. c:\program files\sub.exe
3. c:\program files\sub dir\program.exe
4. c:\program files\sub dir\program name.exe
To run a batch file, you must start the command interpreter; set lpApplicationName to
cmd.exe and set lpCommandLine to the following arguments: /c plus the name of the
batch file.
The maximum length of this string is 32,767 characters, including the Unicode
terminating null character. If lpApplicationName is NULL, the module name portion of
lpCommandLine is limited to MAX_PATH characters.
The Unicode version of this function, CreateProcessW, can modify the contents of this
string. Therefore, this parameter cannot be a pointer to read-only memory (such as a
const variable or a literal string). If this parameter is a constant string, the function may
cause an access violation.
The lpCommandLine parameter can be NULL. In that case, the function uses the string
pointed to by lpApplicationName as the command line.
The system adds a terminating null character to the command-line string to separate
the file name from the arguments. This divides the original string into two strings for
internal processing.
The lpSecurityDescriptor member of the structure specifies a security descriptor for the
new process. If lpProcessAttributes is NULL or lpSecurityDescriptor is NULL, the process
gets a default security descriptor. The ACLs in the default security descriptor for a
process come from the primary token of the creator.Windows XP: The ACLs in the
default security descriptor for a process come from the primary or impersonation token
of the creator. This behavior changed with Windows XP with SP2 and Windows
Server 2003.
The lpSecurityDescriptor member of the structure specifies a security descriptor for the
main thread. If lpThreadAttributes is NULL or lpSecurityDescriptor is NULL, the thread
gets a default security descriptor. The ACLs in the default security descriptor for a thread
come from the process token.Windows XP: The ACLs in the default security descriptor
for a thread come from the primary or impersonation token of the creator. This behavior
changed with Windows XP with SP2 and Windows Server 2003.
[in] bInheritHandles
If this parameter is TRUE, each inheritable handle in the calling process is inherited by
the new process. If the parameter is FALSE, the handles are not inherited. Note that
inherited handles have the same value and access rights as the original handles. For
additional discussion of inheritable handles, see Remarks.
Terminal Services: You cannot inherit handles across sessions. Additionally, if this
parameter is TRUE, you must create the process in the same session as the caller.
Protected Process Light (PPL) processes: The generic handle inheritance is blocked
when a PPL process creates a non-PPL process since PROCESS_DUP_HANDLE is not
allowed from a non-PPL process to a PPL process. See Process Security and Access
Rights
[in] dwCreationFlags
The flags that control the priority class and the creation of the process. For a list of
values, see Process Creation Flags.
This parameter also controls the new process's priority class, which is used to determine
the scheduling priorities of the process's threads. For a list of values, see
GetPriorityClass. If none of the priority class flags is specified, the priority class defaults
to NORMAL_PRIORITY_CLASS unless the priority class of the creating process is
IDLE_PRIORITY_CLASS or BELOW_NORMAL_PRIORITY_CLASS. In this case, the child
process receives the default priority class of the calling process.
The process inherits both the error mode of the caller and the parent's console.
The environment block for the new process is assumed to contain ANSI characters
(see lpEnvironment parameter for additional information).
A 16-bit Windows-based application runs in a shared Virtual DOS machine (VDM).
[in, optional] lpEnvironment
A pointer to the environment block for the new process. If this parameter is NULL, the
new process uses the environment of the calling process.
name=value\0
Because the equal sign is used as a separator, it must not be used in the name of an
environment variable.
An environment block can contain either Unicode or ANSI characters. If the environment
block pointed to by lpEnvironment contains Unicode characters, be sure that
dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT.
The ANSI version of this function, CreateProcessA fails if the total size of the
environment block for the process exceeds 32,767 characters.
Note that an ANSI environment block is terminated by two zero bytes: one for the last
string, one more to terminate the block. A Unicode environment block is terminated by
four zero bytes: two for the last string, two more to terminate the block.
The full path to the current directory for the process. The string can also specify a UNC
path.
If this parameter is NULL, the new process will have the same current drive and directory
as the calling process. (This feature is provided primarily for shells that need to start an
application and specify its initial drive and working directory.)
[in] lpStartupInfo
Important The caller is responsible for ensuring that the standard handle fields in
STARTUPINFO contain valid handle values. These fields are copied unchanged to
the child process without validation, even when the dwFlags member specifies
STARTF_USESTDHANDLES. Incorrect values can cause the child process to
misbehave or crash. Use the Application Verifier runtime verification tool to detect
invalid handles.
[out] lpProcessInformation
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Note that the function returns before the process has finished initialization. If a required
DLL cannot be located or fails to initialize, the process is terminated. To get the
termination status of a process, call GetExitCodeProcess.
Remarks
The process is assigned a process identifier. The identifier is valid until the process
terminates. It can be used to identify the process, or specified in the OpenProcess
function to open a handle to the process. The initial thread in the process is also
assigned a thread identifier. It can be specified in the OpenThread function to open a
handle to the thread. The identifier is valid until the thread terminates and can be used
to uniquely identify the thread within the system. These identifiers are returned in the
PROCESS_INFORMATION structure.
The name of the executable in the command line that the operating system provides to
a process is not necessarily identical to that in the command line that the calling process
gives to the CreateProcess function. The operating system may prepend a fully qualified
path to an executable name that is provided without a fully qualified path.
The calling thread can use the WaitForInputIdle function to wait until the new process
has finished its initialization and is waiting for user input with no input pending. This can
be useful for synchronization between parent and child processes, because
CreateProcess returns without waiting for the new process to finish its initialization. For
example, the creating process would use WaitForInputIdle before trying to find a
window associated with the new process.
The preferred way to shut down a process is by using the ExitProcess function, because
this function sends notification of approaching termination to all DLLs attached to the
process. Other means of shutting down a process do not notify the attached DLLs. Note
that when a thread calls ExitProcess, other threads of the process are terminated
without an opportunity to execute any additional code (including the thread termination
code of attached DLLs). For more information, see Terminating a Process.
A parent process can directly alter the environment variables of a child process during
process creation. This is the only situation when a process can directly change the
environment settings of another process. For more information, see Changing
Environment Variables.
One way to obtain the current directory information for a drive X is to make the
following call: GetFullPathName("X:", ...) . That avoids an application having to scan
the environment block. If the full path returned is X:, there is no need to pass that value
on as environment data, since the root directory is the default current directory for drive
X of a new process.
By default, passing TRUE as the value of the bInheritHandles parameter causes all
inheritable handles to be inherited by the new process. This can be problematic for
applications which create processes from multiple threads simultaneously yet desire
each process to inherit different handles. Applications can use the
UpdateProcThreadAttributeList function with the
PROC_THREAD_ATTRIBUTE_HANDLE_LIST parameter to provide a list of handles to be
inherited by a particular process.
Security Remarks
The first parameter, lpApplicationName, can be NULL, in which case the executable
name must be in the white space–delimited string pointed to by lpCommandLine. If the
executable or path name has a space in it, there is a risk that a different executable
could be run because of the way the function parses spaces. The following example is
dangerous because the function will attempt to run "Program.exe", if it exists, instead of
"MyApp.exe".
syntax
To avoid this problem, do not pass NULL for lpApplicationName. If you do pass NULL for
lpApplicationName, use quotation marks around the executable path in lpCommandLine,
as shown in the example below.
syntax
Examples
7 Note
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
CloseHandle
ShellExecuteW
CreateProcessAsUser
CreateProcessWithLogonW
ExitProcess
GetCommandLine
GetEnvironmentStrings
GetExitCodeProcess
GetFullPathName
GetStartupInfo
OpenProcess
PROCESS_INFORMATION
Processes
SECURITY_ATTRIBUTES
STARTUPINFO
STARTUPINFOEX
SetErrorMode
TerminateProcess
WaitForInputIdle
Feedback
Was this page helpful? ツ Yes ト No
Creates a thread that runs in the virtual address space of another process.
Use the CreateRemoteThreadEx function to create a thread that runs in the virtual
address space of another process and optionally specify extended attributes.
Syntax
C++
HANDLE CreateRemoteThread(
[in] HANDLE hProcess,
[in] LPSECURITY_ATTRIBUTES lpThreadAttributes,
[in] SIZE_T dwStackSize,
[in] LPTHREAD_START_ROUTINE lpStartAddress,
[in] LPVOID lpParameter,
[in] DWORD dwCreationFlags,
[out] LPDWORD lpThreadId
);
Parameters
[in] hProcess
A handle to the process in which the thread is to be created. The handle must have the
PROCESS_CREATE_THREAD, PROCESS_QUERY_INFORMATION,
PROCESS_VM_OPERATION, PROCESS_VM_WRITE, and PROCESS_VM_READ access
rights, and may fail without these rights on certain platforms. For more information, see
Process Security and Access Rights.
[in] lpThreadAttributes
[in] dwStackSize
The initial size of the stack, in bytes. The system rounds this value to the nearest page. If
this parameter is 0 (zero), the new thread uses the default size for the executable. For
more information, see Thread Stack Size.
[in] lpStartAddress
[in] lpParameter
[in] dwCreationFlags
Value Meaning
[out] lpThreadId
Return value
If the function succeeds, the return value is a handle to the new thread.
If the function fails, the return value is NULL. To get extended error information, call
GetLastError.
Note that CreateRemoteThread may succeed even if lpStartAddress points to data, code,
or is not accessible. If the start address is invalid when the thread runs, an exception
occurs, and the thread terminates. Thread termination due to a invalid start address is
handled as an error exit for the thread's process. This behavior is similar to the
asynchronous nature of CreateProcess, where the process is created even if it refers to
invalid or missing dynamic-link libraries (DLL).
Remarks
The CreateRemoteThread function causes a new thread of execution to begin in the
address space of the specified process. The thread has access to all objects that the
process opens.
The new thread handle is created with full access to the new thread. If a security
descriptor is not provided, the handle may be used in any function that requires a
thread object handle. When a security descriptor is provided, an access check is
performed on all subsequent uses of the handle before access is granted. If the access
check denies access, the requesting process cannot use the handle to gain access to the
thread.
If the thread is created in a runnable state (that is, if the CREATE_SUSPENDED flag is not
used), the thread can start running before CreateThread returns and, in particular, before
the caller receives the handle and identifier of the created thread.
When a thread terminates, the thread object attains a signaled state, which satisfies the
threads that are waiting for the object.
The thread object remains in the system until the thread has terminated and all handles
to it are closed through a call to CloseHandle.
During process startup and DLL initialization routines, new threads can be created,
but they do not begin execution until DLL initialization is done for the process.
Only one thread in a process can be in a DLL initialization or detach routine at a
time.
ExitProcess returns after all threads have completed their DLL initialization or
detach routines.
A common use of this function is to inject a thread into a process that is being
debugged to issue a break. However, this use is not recommended, because the extra
thread is confusing to the person debugging the application and there are several side
effects to using this technique:
Another common use of this function is to inject a thread into a process to query heap
or other process information. This can cause the same side effects mentioned in the
previous paragraph. Also, the application can deadlock if the thread attempts to obtain
ownership of locks that another thread is using.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
CloseHandle
CreateProcess
CreateRemoteThreadEx
CreateThread
ExitProcess
ExitThread
GetThreadPriority
ResumeThread
SECURITY_ATTRIBUTES
SetThreadPriority
ThreadProc
Threads
Feedback
Was this page helpful? ツ Yes ト No
Creates a thread that runs in the virtual address space of another process and optionally
specifies extended attributes such as processor group affinity.
Syntax
C++
HANDLE CreateRemoteThreadEx(
[in] HANDLE hProcess,
[in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes,
[in] SIZE_T dwStackSize,
[in] LPTHREAD_START_ROUTINE lpStartAddress,
[in, optional] LPVOID lpParameter,
[in] DWORD dwCreationFlags,
[in, optional] LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList,
[out, optional] LPDWORD lpThreadId
);
Parameters
[in] hProcess
A handle to the process in which the thread is to be created. The handle must have the
PROCESS_CREATE_THREAD, PROCESS_QUERY_INFORMATION,
PROCESS_VM_OPERATION, PROCESS_VM_WRITE, and PROCESS_VM_READ access rights.
In Windows 10, version 1607, your code must obtain these access rights for the new
handle. However, starting in Windows 10, version 1703, if the new handle is entitled to
these access rights, the system obtains them for you. For more information, see Process
Security and Access Rights.
The initial size of the stack, in bytes. The system rounds this value to the nearest page. If
this parameter is 0 (zero), the new thread uses the default size for the executable. For
more information, see Thread Stack Size.
[in] lpStartAddress
[in] dwCreationFlags
Value Meaning
An attribute list that contains additional parameters for the new thread. This list is
created by the InitializeProcThreadAttributeList function.
Return value
If the function succeeds, the return value is a handle to the new thread.
If the function fails, the return value is NULL. To get extended error information, call
GetLastError.
Remarks
The CreateRemoteThreadEx function causes a new thread of execution to begin in the
address space of the specified process. The thread has access to all objects that the
process opens. The lpAttribute parameter can be used to specify extended attributes
such as processor group affinity for the new thread. If lpAttribute is NULL, the function's
behavior is the same as CreateRemoteThread.
The new thread handle is created with full access to the new thread. If a security
descriptor is not provided, the handle may be used in any function that requires a
thread object handle. When a security descriptor is provided, an access check is
performed on all subsequent uses of the handle before access is granted. If the access
check denies access, the requesting process cannot use the handle to gain access to the
thread.
If the thread is created in a runnable state (that is, if the CREATE_SUSPENDED flag is not
used), the thread can start running before CreateThread returns and, in particular, before
the caller receives the handle and identifier of the created thread.
When a thread terminates, the thread object attains a signaled state, which satisfies the
threads that are waiting for the object.
The thread object remains in the system until the thread has terminated and all handles
to it are closed through a call to CloseHandle.
A common use of this function is to inject a thread into a process that is being
debugged to issue a break. However, this use is not recommended, because the extra
thread is confusing to the person debugging the application and there are several side
effects to using this technique:
Another common use of this function is to inject a thread into a process to query heap
or other process information. This can cause the same side effects mentioned in the
previous paragraph. Also, the application can deadlock if the thread attempts to obtain
ownership of locks that another thread is using.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
CreateRemoteThread
Feedback
Was this page helpful? ツ Yes ト No
Creates a thread to execute within the virtual address space of the calling process.
To create a thread that runs in the virtual address space of another process, use the
CreateRemoteThread function.
Syntax
C++
HANDLE CreateThread(
[in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes,
[in] SIZE_T dwStackSize,
[in] LPTHREAD_START_ROUTINE lpStartAddress,
[in, optional] __drv_aliasesMem LPVOID lpParameter,
[in] DWORD dwCreationFlags,
[out, optional] LPDWORD lpThreadId
);
Parameters
[in, optional] lpThreadAttributes
The lpSecurityDescriptor member of the structure specifies a security descriptor for the
new thread. If lpThreadAttributes is NULL, the thread gets a default security descriptor.
The ACLs in the default security descriptor for a thread come from the primary token of
the creator.
[in] dwStackSize
The initial size of the stack, in bytes. The system rounds this value to the nearest page. If
this parameter is zero, the new thread uses the default size for the executable. For more
information, see Thread Stack Size.
[in] lpStartAddress
A pointer to the application-defined function to be executed by the thread. This pointer
represents the starting address of the thread. For more information on the thread
function, see ThreadProc.
[in] dwCreationFlags
Value Meaning
A pointer to a variable that receives the thread identifier. If this parameter is NULL, the
thread identifier is not returned.
Return value
If the function succeeds, the return value is a handle to the new thread.
If the function fails, the return value is NULL. To get extended error information, call
GetLastError.
Note that CreateThread may succeed even if lpStartAddress points to data, code, or is
not accessible. If the start address is invalid when the thread runs, an exception occurs,
and the thread terminates. Thread termination due to a invalid start address is handled
as an error exit for the thread's process. This behavior is similar to the asynchronous
nature of CreateProcess, where the process is created even if it refers to invalid or
missing dynamic-link libraries (DLLs).
Remarks
The number of threads a process can create is limited by the available virtual memory.
By default, every thread has one megabyte of stack space. Therefore, you cannot create
2,048 or more threads on a 32-bit system without /3GB boot.ini option. If you reduce
the default stack size, you can create more threads. However, your application will have
better performance if you create one thread per processor and build queues of requests
for which the application maintains the context information. A thread would process all
requests in a queue before processing requests in the next queue.
The new thread handle is created with the THREAD_ALL_ACCESS access right. If a
security descriptor is not provided when the thread is created, a default security
descriptor is constructed for the new thread using the primary token of the process that
is creating the thread. When a caller attempts to access the thread with the OpenThread
function, the effective token of the caller is evaluated against this security descriptor to
grant or deny access.
The newly created thread has full access rights to itself when calling the
GetCurrentThread function.
Windows Server 2003: The thread's access rights to itself are computed by evaluating
the primary token of the process in which the thread was created against the default
security descriptor constructed for the thread. If the thread is created in a remote
process, the primary token of the remote process is used. As a result, the newly created
thread may have reduced access rights to itself when calling GetCurrentThread. Some
access rights including THREAD_SET_THREAD_TOKEN and THREAD_GET_CONTEXT
may not be present, leading to unexpected failures. For this reason, creating a thread
while impersonating another user is not recommended.
If the thread is created in a runnable state (that is, if the CREATE_SUSPENDED flag is not
used), the thread can start running before CreateThread returns and, in particular,
before the caller receives the handle and identifier of the created thread.
The thread execution begins at the function specified by the lpStartAddress parameter. If
this function returns, the DWORD return value is used to terminate the thread in an
implicit call to the ExitThread function. Use the GetExitCodeThread function to get the
thread's return value.
When a thread terminates, the thread object attains a signaled state, satisfying any
threads that were waiting on the object.
The thread object remains in the system until the thread has terminated and all handles
to it have been closed through a call to CloseHandle.
During process startup and DLL initialization routines, new threads can be created,
but they do not begin execution until DLL initialization is done for the process.
Only one thread in a process can be in a DLL initialization or detach routine at a
time.
ExitProcess does not complete until there are no threads in their DLL initialization
or detach routines.
A thread in an executable that calls the C run-time library (CRT) should use the
_beginthreadex and _endthreadex functions for thread management rather than
CreateThread and ExitThread; this requires the use of the multithreaded version of the
CRT. If a thread created using CreateThread calls the CRT, the CRT may terminate the
process in low-memory conditions.
Windows Phone 8.1: This function is supported for Windows Phone Store apps on
Windows Phone 8.1 and later.
Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows
Store apps on Windows 8.1, Windows Server 2012 R2, and later.
Examples
Requirements
See also
CloseHandle
CreateProcess
CreateRemoteThread
ExitProcess
ExitThread
GetExitCodeThread
GetThreadPriority
ResumeThread
SECURITY_ATTRIBUTES
SetThreadPriority
SuspendThread
ThreadProc
Threads
Feedback
Was this page helpful? Yes No
DeleteProcThreadAttributeList function
(processthreadsapi.h)
Article11/01/2022
Deletes the specified list of attributes for process and thread creation.
Syntax
C++
void DeleteProcThreadAttributeList(
[in, out] LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList
);
Parameters
[in, out] lpAttributeList
Return value
None
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
InitializeProcThreadAttributeList
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
void ExitProcess(
[in] UINT uExitCode
);
Parameters
[in] uExitCode
Return value
None
Remarks
Use the GetExitCodeProcess function to retrieve the process's exit value. Use the
GetExitCodeThread function to retrieve a thread's exit value.
1. All of the threads in the process, except the calling thread, terminate their
execution without receiving a DLL_THREAD_DETACH notification.
2. The states of all of the threads terminated in step 1 become signaled.
3. The entry-point functions of all loaded dynamic-link libraries (DLLs) are called with
DLL_PROCESS_DETACH.
4. After all attached DLLs have executed any process termination code, the
ExitProcess function terminates the current process, including the calling thread.
5. The state of the calling thread becomes signaled.
6. All of the object handles opened by the process are closed.
7. The termination status of the process changes from STILL_ACTIVE to the exit value
of the process.
8. The state of the process object becomes signaled, satisfying any threads that had
been waiting for the process to terminate.
If one of the terminated threads in the process holds a lock and the DLL detach code in
one of the loaded DLLs attempts to acquire the same lock, then calling ExitProcess
results in a deadlock. In contrast, if a process terminates by calling TerminateProcess, the
DLLs that the process is attached to are not notified of the process termination.
Therefore, if you do not know the state of all threads in your process, it is better to call
TerminateProcess than ExitProcess. Note that returning from the main function of an
application results in a call to ExitProcess.
Calling ExitProcess in a DLL can lead to unexpected application or system errors. Be sure
to call ExitProcess from a DLL only if you know which applications or system
components will load the DLL and that it is safe to call ExitProcess in this context.
Exiting a process does not necessarily remove the process object from the operating
system. A process object is deleted when the last handle to the process is closed.
Examples
For an example, see Creating a Child Process with Redirected Input and Output.
Requirements
Target Windows
Platform
DLL Kernel32.dll
See also
CreateProcess
CreateRemoteThread
CreateThread
ExitThread
GetExitCodeProcess
GetExitCodeThread
OpenProcess
Processes
TerminateProcess
Terminating a Process
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
void ExitThread(
[in] DWORD dwExitCode
);
Parameters
[in] dwExitCode
Return value
None
Remarks
ExitThread is the preferred method of exiting a thread in C code. However, in C++ code,
the thread is exited before any destructors can be called or any other automatic cleanup
can be performed. Therefore, in C++ code, you should return from your thread function.
When this function is called (either explicitly or by returning from a thread procedure),
the current thread's stack is deallocated, all pending I/O initiated by the thread that is
not associated with a completion port is canceled, and the thread terminates. The entry-
point function of all attached dynamic-link libraries (DLLs) is invoked with a value
indicating that the thread is detaching from the DLL.
If the thread is the last thread in the process when this function is called, the thread's
process is also terminated.
The state of the thread object becomes signaled, releasing any other threads that had
been waiting for the thread to terminate. The thread's termination status changes from
STILL_ACTIVE to the value of the dwExitCode parameter.
Terminating a thread does not necessarily remove the thread object from the operating
system. A thread object is deleted when the last handle to the thread is closed.
During process startup and DLL initialization routines, new threads can be created,
but they do not begin execution until DLL initialization is done for the process.
Only one thread in a process can be in a DLL initialization or detach routine at a
time.
ExitProcess does not return until no threads are in their DLL initialization or detach
routines.
A thread in an executable that is linked to the static C run-time library (CRT) should use
_beginthread and _endthread for thread management rather than CreateThread and
ExitThread. Failure to do so results in small memory leaks when the thread calls
ExitThread. Another work around is to link the executable to the CRT in a DLL instead of
the static CRT. Note that this memory leak only occurs from a DLL if the DLL is linked to
the static CRT and a thread calls the DisableThreadLibraryCalls function. Otherwise, it is
safe to call CreateThread and ExitThread from a thread in a DLL that links to the static
CRT.
Windows Phone 8.1: This function is supported for Windows Phone Store apps on
Windows Phone 8.1 and later.
Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows
Store apps on Windows 8.1, Windows Server 2012 R2, and later.
Examples
For an example, see Using Event Objects.
Requirements
Minimum Windows XP [desktop apps | UWP apps]
supported
client
Target Windows
Platform
See also
CreateProcess
CreateRemoteThread
CreateThread
ExitProcess
FreeLibraryAndExitThread
GetExitCodeThread
OpenThread
TerminateThread
Threads
Feedback
Was this page helpful? ツ Yes ト No
Get help at Microsoft Q&A
FlushProcessWriteBuffers function
(processthreadsapi.h)
Article11/01/2022
Flushes the write queue of each processor that is running a thread of the current
process.
Syntax
C++
void FlushProcessWriteBuffers();
Return value
None
Remarks
The function generates an interprocessor interrupt (IPI) to all processors that are part of
the current process affinity. It guarantees the visibility of write operations performed on
one processor to the other processors.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
Process and Thread Functions
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
HANDLE GetCurrentProcess();
Return value
The return value is a pseudo handle to the current process.
Remarks
A pseudo handle is a special constant, currently (HANDLE)-1, that is interpreted as the
current process handle. For compatibility with future operating systems, it is best to call
GetCurrentProcess instead of hard-coding this constant value. The calling process can
use a pseudo handle to specify its own process whenever a process handle is required.
Pseudo handles are not inherited by child processes.
This handle has the PROCESS_ALL_ACCESS access right to the process object. For more
information, see Process Security and Access Rights.
Windows Server 2003 and Windows XP: This handle has the maximum access allowed
by the security descriptor of the process to the primary token of the process.
A process can create a "real" handle to itself that is valid in the context of other
processes, or that can be inherited by other processes, by specifying the pseudo handle
as the source handle in a call to the DuplicateHandle function. A process can also use
the OpenProcess function to open a real handle to itself.
The pseudo handle need not be closed when it is no longer needed. Calling the
CloseHandle function with a pseudo handle has no effect. If the pseudo handle is
duplicated by DuplicateHandle, the duplicate handle must be closed.
Examples
For an example, see Creating a Child Process with Redirected Input and Output.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
CloseHandle
DuplicateHandle
GetCurrentProcessId
GetCurrentThread
OpenProcess
Processes
Feedback
ツY トN
ツ Yes ト No
Was this page helpful?
Syntax
C++
DWORD GetCurrentProcessId();
Return value
The return value is the process identifier of the calling process.
Remarks
Until the process terminates, the process identifier uniquely identifies the process
throughout the system.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
GetCurrentProcess
OpenProcess
Processes
Feedback
Was this page helpful? ツ Yes ト No
Retrieves the number of the processor the current thread was running on during the call
to this function.
Syntax
C++
DWORD GetCurrentProcessorNumber();
Return value
The function returns the current processor number.
Remarks
This function is used to provide information for estimating process performance.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
Multiple Processors
Processes
Feedback
Was this page helpful? ツ Yes ト No
Retrieves the processor group and number of the logical processor in which the calling
thread is running.
Syntax
C++
void GetCurrentProcessorNumberEx(
[out] PPROCESSOR_NUMBER ProcNumber
);
Parameters
[out] ProcNumber
Return value
None
Remarks
To compile an application that uses this function, set _WIN32_WINNT >= 0x0601. For
more information, see Using the Windows Headers.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
HANDLE GetCurrentThread();
Return value
The return value is a pseudo handle for the current thread.
Remarks
A pseudo handle is a special constant that is interpreted as the current thread handle.
The calling thread can use this handle to specify itself whenever a thread handle is
required. Pseudo handles are not inherited by child processes.
This handle has the THREAD_ALL_ACCESS access right to the thread object. For more
information, see Thread Security and Access Rights.
Windows Server 2003 and Windows XP: This handle has the maximum access allowed
by the security descriptor of the thread to the primary token of the process.
The function cannot be used by one thread to create a handle that can be used by other
threads to refer to the first thread. The handle is always interpreted as referring to the
thread that is using it. A thread can create a "real" handle to itself that can be used by
other threads, or inherited by other processes, by specifying the pseudo handle as the
source handle in a call to the DuplicateHandle function.
The pseudo handle need not be closed when it is no longer needed. Calling the
CloseHandle function with this handle has no effect. If the pseudo handle is duplicated
by DuplicateHandle, the duplicate handle must be closed.
Do not create a thread while impersonating a security context. The call will succeed,
however the newly created thread will have reduced access rights to itself when calling
GetCurrentThread. The access rights granted this thread will be derived from the access
rights the impersonated user has to the process. Some access rights including
THREAD_SET_THREAD_TOKEN and THREAD_GET_CONTEXT may not be present,
leading to unexpected failures.
Examples
For an example, see Checking Client Access.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
CloseHandle
DuplicateHandle
GetCurrentProcess
GetCurrentThreadId
OpenThread
Process and Thread Functions
Threads
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
DWORD GetCurrentThreadId();
Return value
The return value is the thread identifier of the calling thread.
Remarks
Until the thread terminates, the thread identifier uniquely identifies the thread
throughout the system.
Examples
For an example, see Using Thread Local Storage.
Requirements
Target Windows
Platform
Header processthreadsapi.h (include Windows.h on Windows Server 2003,
Windows Vista, Windows 7, Windows Server 2008 Windows Server 2008 R2)
Library Kernel32.lib
DLL Kernel32.dll
See also
GetCurrentThread
OpenThread
Threads
Feedback
Was this page helpful? ツ Yes ト No
Retrieves the boundaries of the stack that was allocated by the system for the current
thread.
Syntax
C++
void GetCurrentThreadStackLimits(
[out] PULONG_PTR LowLimit,
[out] PULONG_PTR HighLimit
);
Parameters
[out] LowLimit
A pointer variable that receives the lower boundary of the current thread stack.
[out] HighLimit
A pointer variable that receives the upper boundary of the current thread stack.
Return value
None
Remarks
It is possible for user-mode code to execute in stack memory that is outside the region
allocated by the system when the thread was created. Callers can use the
GetCurrentThreadStackLimits function to verify that the current stack pointer is within
the returned limits.
To compile an application that uses this function, set _WIN32_WINNT >= 0x0602. For
more information, see Using the Windows Headers.
Requirements
Minimum supported server Windows Server 2012 [desktop apps | UWP apps]
Header processthreadsapi.h
Library Kernel32.lib
DLL Kernel32.dll
See also
Thread Stack Size
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL GetExitCodeProcess(
[in] HANDLE hProcess,
[out] LPDWORD lpExitCode
);
Parameters
[in] hProcess
Windows Server 2003 and Windows XP: The handle must have the
PROCESS_QUERY_INFORMATION access right.
[out] lpExitCode
A pointer to a variable to receive the process termination status. For more information,
see Remarks.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
This function returns immediately. If the process has not terminated and the function
succeeds, the status returned is STILL_ACTIVE (a macro for STATUS_PENDING
(minwinbase.h)). If the process has terminated and the function succeeds, the status
returned is one of the following values:
) Important
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
ExitProcess
ExitThread
Processes
TerminateProcess
Terminating a Process
WinMain
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL GetExitCodeThread(
[in] HANDLE hThread,
[out] LPDWORD lpExitCode
);
Parameters
[in] hThread
Windows Server 2003 and Windows XP: The handle must have the
THREAD_QUERY_INFORMATION access right.
[out] lpExitCode
A pointer to a variable to receive the thread termination status. For more information,
see Remarks.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
This function returns immediately. If the specified thread has not terminated and the
function succeeds, the status returned is STILL_ACTIVE. If the thread has terminated and
the function succeeds, the status returned is one of the following values:
Windows Phone 8.1: This function is supported for Windows Phone Store apps on
Windows Phone 8.1 and later.
Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows
Store apps on Windows 8.1, Windows Server 2012 R2, and later.
Requirements
Target Windows
Platform
Header processthreadsapi.h (include Windows.h on Windows Server 2003,
Windows Vista, Windows 7, Windows Server 2008 Windows Server 2008 R2)
See also
ExitThread
GetExitCodeProcess
OpenThread
TerminateThread
Terminating a Thread
Feedback
Was this page helpful? ツ Yes ト No
Retrieves the priority class for the specified process. This value, together with the priority
value of each thread of the process, determines each thread's base priority level.
Syntax
C++
DWORD GetPriorityClass(
[in] HANDLE hProcess
);
Parameters
[in] hProcess
Windows Server 2003 and Windows XP: The handle must have the
PROCESS_QUERY_INFORMATION access right.
Return value
If the function succeeds, the return value is the priority class of the specified process.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
IDLE_PRIORITY_CLASS Process whose threads run only when the system is idle
0x00000040 and are preempted by the threads of any process running
in a higher priority class. An example is a screen saver.
The idle priority class is inherited by child processes.
REALTIME_PRIORITY_CLASS Process that has the highest possible priority. The threads
0x00000100 of a real-time priority class process preempt the threads
of all other processes, including operating system
processes performing important tasks. For example, a
real-time process that executes for more than a very brief
interval can cause disk caches not to flush or cause the
mouse to be unresponsive.
Remarks
Every thread has a base priority level determined by the thread's priority value and the
priority class of its process. The operating system uses the base priority level of all
executable threads to determine which thread gets the next slice of CPU time. Threads
are scheduled in a round-robin fashion at each priority level, and only when there are no
executable threads at a higher level will scheduling of threads at a lower level take place.
For a table that shows the base priority levels for each combination of priority class and
thread priority value, see Scheduling Priorities.
Priority class is maintained by the executive, so all processes have a priority class that
can be queried.
Examples
For an example, see Taking a Snapshot and Viewing Processes.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
GetThreadPriority
Processes
Scheduling Priorities
SetPriorityClass
SetThreadPriority
Feedback
Was this page helpful? ツ Yes ト No
Retrieves the number of open handles that belong to the specified process.
Syntax
C++
BOOL GetProcessHandleCount(
[in] HANDLE hProcess,
[in, out] PDWORD pdwHandleCount
);
Parameters
[in] hProcess
A handle to the process whose handle count is being requested. The handle must have
the PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION
access right. For more information, see Process Security and Access Rights.
Windows Server 2003 and Windows XP: The handle must have the
PROCESS_QUERY_INFORMATION access right.
A pointer to a variable that receives the number of open handles that belong to the
specified process.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
This function retrieves information about the executive objects for the process. For more
information, see Kernel Objects.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
Process and Thread Functions
Processes
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
DWORD GetProcessId(
[in] HANDLE Process
);
Parameters
[in] Process
Windows Server 2003 and Windows XP: The handle must have the
PROCESS_QUERY_INFORMATION access right.
Return value
If the function succeeds, the return value is the process identifier.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
Until a process terminates, its process identifier uniquely identifies it on the system. For
more information about access rights, see Process Security and Access Rights.
Requirements
Minimum Windows Vista, Windows XP with SP1 [desktop apps | UWP apps]
supported
client
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
GetCurrentProcessId
GetProcessIdOfThread
GetThreadId
Processes
Feedback
Was this page helpful? ツ Yes ト No
Retrieves the process identifier of the process associated with the specified thread.
Syntax
C++
DWORD GetProcessIdOfThread(
[in] HANDLE Thread
);
Parameters
[in] Thread
Return value
If the function succeeds, the return value is the process identifier of the process
associated with the specified thread.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
Until a process terminates, its process identifier uniquely identifies it on the system. For
more information about access rights, see Thread Security and Access Rights.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
GetCurrentThreadId
GetProcessId
GetThreadId
Processes
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL GetProcessInformation(
[in] HANDLE hProcess,
[in] PROCESS_INFORMATION_CLASS ProcessInformationClass,
LPVOID ProcessInformation,
[in] DWORD ProcessInformationSize
);
Parameters
[in] hProcess
[in] ProcessInformationClass
ProcessInformation
[in] ProcessInformationSize
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError function.
Requirements
Minimum supported server Windows Server 2012 [desktop apps | UWP apps]
Library Kernel32.lib
DLL Kernel32.dll
See also
GetThreadInformation function, MEMORY_PRIORITY_INFORMATION structure,
SetProcessInformation function, PROCESS_INFORMATION_CLASS enumeration
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL GetProcessMitigationPolicy(
[in] HANDLE hProcess,
[in] PROCESS_MITIGATION_POLICY MitigationPolicy,
[out] PVOID lpBuffer,
[in] SIZE_T dwLength
);
Parameters
[in] hProcess
[in] MitigationPolicy
The mitigation policy to retrieve. This parameter can be one of the following values.
Value Meaning
ProcessDynamicCodePolicy The dynamic code policy of the process. When turned on,
the process cannot generate dynamic code or modify
existing executable code.
The lpBuffer parameter points to a
PROCESS_MITIGATION_DYNAMIC_CODE_POLICY structure
that specifies the dynamic code policy flags.
ProcessMitigationOptionsMask Returns the mask of valid bits for all the mitigation options
on the system. An application can set many mitigation
options without querying the operating system for
mitigation options by combining bitwise with the mask to
exclude all non-supported bits at once.
The lpBuffer parameter points to a ULONG64 bit vector for
the mask, or a two-element array of ULONG64 bit vectors.
ProcessFontDisablePolicy The policy regarding font loading for the process. When
turned on, the process cannot load non-system fonts.
The lpBuffer parameter points to a
PROCESS_MITIGATION_FONT_DISABLE_POLICY structure
that specifies the policy flags for font loading.
ProcessImageLoadPolicy The policy regarding image loading for the process, which
determines the types of executable images that are allowed
to be mapped into the process. When turned on, images
cannot be loaded from some locations, such a remote
devices or files that have the low mandatory label.
The lpBuffer parameter points to a
PROCESS_MITIGATION_IMAGE_LOAD_POLICY structure that
specifies the policy flags for image loading.
ProcessSideChannelIsolationPolicy Windows 10, version 1809 and above: The policy regarding
isolation of side channels for the specified process.
The lpBuffer parameter points to a
PROCESS_MITIGATION_SIDE_CHANNEL_ISOLATION_POLICY
structure that specifies the policy flags for side channel
isolation.
ProcessUserShadowStackPolicy Windows 10, version 2004 and above: The policy regarding
user-mode Hardware-enforced Stack Protection for the
specified process.
The lpBuffer parameter points to a
PROCESS_MITIGATION_USER_SHADOW_STACK_POLICY
structure that specifies the policy flags for user-mode
Hardware-enforced Stack Protection.
[out] lpBuffer
[in] dwLength
Remarks
To compile an application that uses this function, set _WIN32_WINNT >= 0x0602. For
more information, see Using the Windows Headers.
Requirements
Minimum supported server Windows Server 2012 [desktop apps | UWP apps]
Header processthreadsapi.h
Library Kernel32.lib
DLL Kernel32.dll
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL GetProcessPriorityBoost(
[in] HANDLE hProcess,
[out] PBOOL pDisablePriorityBoost
);
Parameters
[in] hProcess
Windows Server 2003 and Windows XP: The handle must have the
PROCESS_QUERY_INFORMATION access right.
[out] pDisablePriorityBoost
A pointer to a variable that receives the priority boost control state. A value of TRUE
indicates that dynamic boosting is disabled. A value of FALSE indicates normal behavior.
Return value
If the function succeeds, the return value is nonzero. In that case, the variable pointed to
by the pDisablePriorityBoost parameter receives the priority boost control state.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Requirements
Minimum supported server Windows Server 2003 [desktop apps | UWP apps]
Library Kernel32.lib
DLL Kernel32.dll
See also
Priority Boosts
Processes
Scheduling Priorities
SetProcessPriorityBoost
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL GetProcessShutdownParameters(
[out] LPDWORD lpdwLevel,
[out] LPDWORD lpdwFlags
);
Parameters
[out] lpdwLevel
A pointer to a variable that receives the shutdown priority level. Higher levels shut down
first. System level shutdown orders are reserved for system components. Higher
numbers shut down first. Following are the level conventions.
Value Meaning
[out] lpdwFlags
A pointer to a variable that receives the shutdown flags. This parameter can be the
following value.
Value Meaning
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
Process and Thread Functions
Processes
SetProcessShutdownParameters
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL GetProcessTimes(
[in] HANDLE hProcess,
[out] LPFILETIME lpCreationTime,
[out] LPFILETIME lpExitTime,
[out] LPFILETIME lpKernelTime,
[out] LPFILETIME lpUserTime
);
Parameters
[in] hProcess
A handle to the process whose timing information is sought. The handle must have the
PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access
right. For more information, see Process Security and Access Rights.
Windows Server 2003 and Windows XP: The handle must have the
PROCESS_QUERY_INFORMATION access right.
[out] lpCreationTime
A pointer to a FILETIME structure that receives the creation time of the process.
[out] lpExitTime
A pointer to a FILETIME structure that receives the exit time of the process. If the process
has not exited, the content of this structure is undefined.
[out] lpKernelTime
A pointer to a FILETIME structure that receives the amount of time that the process has
executed in kernel mode. The time that each of the threads of the process has executed
in kernel mode is determined, and then all of those times are summed together to
obtain this value.
[out] lpUserTime
A pointer to a FILETIME structure that receives the amount of time that the process has
executed in user mode. The time that each of the threads of the process has executed in
user mode is determined, and then all of those times are summed together to obtain
this value. Note that this value can exceed the amount of real time elapsed (between
lpCreationTime and lpExitTime) if the process executes across multiple CPU cores.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
All times are expressed using FILETIME data structures. Such a structure contains two
32-bit values that combine to form a 64-bit count of 100-nanosecond time units.
Process creation and exit times are points in time expressed as the amount of time that
has elapsed since midnight on January 1, 1601 at Greenwich, England. There are several
functions that an application can use to convert such values to more generally useful
forms.
Process kernel mode and user mode times are amounts of time. For example, if a
process has spent one second in kernel mode, this function will fill the FILETIME
structure specified by lpKernelTime with a 64-bit value of ten million. That is the number
of 100-nanosecond units in one second.
To retrieve the number of CPU clock cycles used by the threads of the process, use the
QueryProcessCycleTime function.
Requirements
Minimum Windows XP [desktop apps | UWP apps]
supported
client
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
FILETIME
FileTimeToDosDateTime
FileTimeToLocalFileTime
FileTimeToSystemTime
Processes
Feedback
Was this page helpful? ツ Yes ト No
Retrieves the major and minor version numbers of the system on which the specified
process expects to run.
Syntax
C++
DWORD GetProcessVersion(
[in] DWORD ProcessId
);
Parameters
[in] ProcessId
The process identifier of the process of interest. A value of zero specifies the calling
process.
Return value
If the function succeeds, the return value is the version of the system on which the
process expects to run. The high word of the return value contains the major version
number. The low word of the return value contains the minor version number.
If the function fails, the return value is zero. To get extended error information, call
GetLastError. The function fails if ProcessId is an invalid value.
Remarks
The GetProcessVersion function performs less quickly when ProcessId is nonzero,
specifying a process other than the calling process.
The version number returned by this function is the version number stamped in the
image header of the .exe file the process is running. Linker programs set this value.
If this function is called from a 32-bit application running on WOW64, the specified
process must be a 32-bit process or the function fails.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
Process and Thread Functions
Processes
Feedback
Was this page helpful? ツ Yes ト No
Retrieves the contents of the STARTUPINFO structure that was specified when the calling
process was created.
Syntax
C++
void GetStartupInfoW(
[out] LPSTARTUPINFOW lpStartupInfo
);
Parameters
[out] lpStartupInfo
Return value
None
Remarks
The STARTUPINFO structure was specified by the process that created the calling
process. It can be used to specify properties associated with the main window of the
calling process.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
CreateProcess
Processes
STARTUPINFO
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
HRESULT GetThreadDescription(
[in] HANDLE hThread,
[out] PWSTR *ppszThreadDescription
);
Parameters
[in] hThread
A handle to the thread for which to retrieve the description. The handle must have
THREAD_QUERY_LIMITED_INFORMATION access.
[out] ppszThreadDescription
Return value
If the function succeeds, the return value is the HRESULT that denotes a successful
operation. If the function fails, the return value is an HRESULT that denotes the error.
Remarks
Windows Server 2016, Windows 10 LTSB 2016 and Windows 10 version 1607:
GetThreadDescription is only available by Run Time Dynamic Linking in KernelBase.dll.
The description for a thread can change at any time. For example, a different thread can
change the description of a thread of interest while you try to retrieve that description.
Examples
The following example gets the description for a thread, prints the description, and then
frees the memory for the description.
C++
Requirements
Minimum supported client Windows 10, version 1607 [desktop apps | UWP apps]
Minimum supported server Windows Server 2016 [desktop apps | UWP apps]
Header processthreadsapi.h
Library Kernel32.lib
DLL Kernel32.dll
See also
LocalFree, SetThreadDescription
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
DWORD GetThreadId(
[in] HANDLE Thread
);
Parameters
[in] Thread
Return value
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
Until a thread terminates, its thread identifier uniquely identifies it on the system.
Requirements
Minimum Windows Vista [desktop apps | UWP apps]
supported client
Library Kernel32.lib
DLL Kernel32.dll
See also
GetCurrentThreadId
GetProcessId
GetProcessIdOfThread
Threads
Feedback
Was this page helpful? ツ Yes ト No
Retrieves the processor number of the ideal processor for the specified thread.
Syntax
C++
BOOL GetThreadIdealProcessorEx(
[in] HANDLE hThread,
[out] PPROCESSOR_NUMBER lpIdealProcessor
);
Parameters
[in] hThread
A handle to the thread for which to retrieve the ideal processor. This handle must have
been created with the THREAD_QUERY_LIMITED_INFORMATION access right. For more
information, see Thread Security and Access Rights.
[out] lpIdealProcessor
Return value
If the function succeeds, it returns a nonzero value.
If the function fails, it returns zero. To get extended error information, use GetLastError.
Remarks
To compile an application that uses this function, set _WIN32_WINNT >= 0x0601. For
more information, see Using the Windows Headers.
Requirements
Minimum supported server Windows Server 2008 R2 [desktop apps | UWP apps]
Library Kernel32.lib
DLL Kernel32.dll
See also
SetThreadIdealProcessorEx
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL GetThreadInformation(
[in] HANDLE hThread,
[in] THREAD_INFORMATION_CLASS ThreadInformationClass,
LPVOID ThreadInformation,
[in] DWORD ThreadInformationSize
);
Parameters
[in] hThread
[in] ThreadInformationClass
7 Note
ThreadInformation
[in] ThreadInformationSize
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
GetProcessInformation, SetThreadInformation
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL GetThreadIOPendingFlag(
[in] HANDLE hThread,
[in, out] PBOOL lpIOIsPending
);
Parameters
[in] hThread
A handle to the thread in question. This handle must have been created with the
THREAD_QUERY_INFORMATION access right. For more information, see Thread Security
and Access Rights.
A pointer to a variable which the function sets to TRUE if the specified thread has one or
more I/O requests pending, or to FALSE otherwise.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
Keep in mind that the I/O status of the specified thread can change rapidly, and may
already have changed by the time the function returns. For example, a pending I/O
operation could complete between the time the function sets lpIOIsPending and the
time it returns.
Requirements
Minimum supported client Windows Vista, Windows XP with SP1 [desktop apps only]
Library Kernel32.lib
DLL Kernel32.dll
See also
Process and Thread Functions
Threads
Feedback
Was this page helpful? ツ Yes ト No
Retrieves the priority value for the specified thread. This value, together with the priority
class of the thread's process, determines the thread's base-priority level.
Syntax
C++
int GetThreadPriority(
[in] HANDLE hThread
);
Parameters
[in] hThread
Return value
If the function succeeds, the return value is the thread's priority level.
If the thread has the REALTIME_PRIORITY_CLASS base class, this function can also
return one of the following values: -7, -6, -5, -4, -3, 3, 4, 5, or 6. For more information,
see Scheduling Priorities.
Remarks
Every thread has a base-priority level determined by the thread's priority value and the
priority class of its process. The operating system uses the base-priority level of all
executable threads to determine which thread gets the next slice of CPU time. Threads
are scheduled in a round-robin fashion at each priority level, and only when there are no
executable threads at a higher level will scheduling of threads at a lower level take place.
For a table that shows the base-priority levels for each combination of priority class and
thread priority value, refer to the SetPriorityClass function.
Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows
Store apps.
Windows Phone 8.1:Windows Phone Store apps may call this function but it has no
effect.
Requirements
Target Windows
Platform
See also
GetPriorityClass
OpenThread
Scheduling Priorities
SetPriorityClass
SetThreadPriority
Threads
Feedback
Was this page helpful? ツ Yes ト No
Get help at Microsoft Q&A
GetThreadPriorityBoost function
(processthreadsapi.h)
Article11/01/2022
Syntax
C++
BOOL GetThreadPriorityBoost(
[in] HANDLE hThread,
[out] PBOOL pDisablePriorityBoost
);
Parameters
[in] hThread
Windows Server 2003 and Windows XP: The handle must have the
THREAD_QUERY_INFORMATION access right.
[out] pDisablePriorityBoost
A pointer to a variable that receives the priority boost control state. A value of TRUE
indicates that dynamic boosting is disabled. A value of FALSE indicates normal behavior.
Return value
If the function succeeds, the return value is nonzero. In that case, the variable pointed to
by the pDisablePriorityBoost parameter receives the priority boost control state.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
OpenThread
Priority Boosts
Scheduling Priorities
SetThreadPriorityBoost
Threads
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL GetThreadTimes(
[in] HANDLE hThread,
[out] LPFILETIME lpCreationTime,
[out] LPFILETIME lpExitTime,
[out] LPFILETIME lpKernelTime,
[out] LPFILETIME lpUserTime
);
Parameters
[in] hThread
A handle to the thread whose timing information is sought. The handle must have the
THREAD_QUERY_INFORMATION or THREAD_QUERY_LIMITED_INFORMATION access
right. For more information, see Thread Security and Access Rights.
Windows Server 2003 and Windows XP: The handle must have the
THREAD_QUERY_INFORMATION access right.
[out] lpCreationTime
A pointer to a FILETIME structure that receives the creation time of the thread.
[out] lpExitTime
A pointer to a FILETIME structure that receives the exit time of the thread. If the thread
has not exited, the content of this structure is undefined.
[out] lpKernelTime
A pointer to a FILETIME structure that receives the amount of time that the thread has
executed in kernel mode.
[out] lpUserTime
A pointer to a FILETIME structure that receives the amount of time that the thread has
executed in user mode.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
All times are expressed using FILETIME data structures. Such a structure contains two
32-bit values that combine to form a 64-bit count of 100-nanosecond time units.
Thread creation and exit times are points in time expressed as the amount of time that
has elapsed since midnight on January 1, 1601 at Greenwich, England. There are several
functions that an application can use to convert such values to more generally useful
forms; see Time Functions.
Thread kernel mode and user mode times are amounts of time. For example, if a thread
has spent one second in kernel mode, this function will fill the FILETIME structure
specified by lpKernelTime with a 64-bit value of ten million. That is the number of 100-
nanosecond units in one second.
To retrieve the number of CPU clock cycles used by the threads, use the
QueryThreadCycleTime function.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
FILETIME
FileTimeToDosDateTime
FileTimeToLocalFileTime
FileTimeToSystemTime
OpenThread
Threads
Feedback
Was this page helpful? ツ Yes ト No
Initializes the specified list of attributes for process and thread creation.
Syntax
C++
BOOL InitializeProcThreadAttributeList(
[out, optional] LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList,
[in] DWORD dwAttributeCount,
DWORD dwFlags,
[in, out] PSIZE_T lpSize
);
Parameters
[out, optional] lpAttributeList
The attribute list. This parameter can be NULL to determine the buffer size required to
support the specified number of attributes.
[in] dwAttributeCount
dwFlags
If lpAttributeList is not NULL, this parameter specifies the size in bytes of the
lpAttributeList buffer on input. On output, this parameter receives the size in bytes of the
initialized attribute list.
If lpAttributeList is NULL, this parameter receives the required buffer size in bytes.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
First, call this function with the dwAttributeCount parameter set to the maximum number
of attributes you will be using and the lpAttributeList to NULL. The function returns the
required buffer size in bytes in the lpSize parameter.
Note This initial call will return an error by design. This is expected behavior.
Allocate enough space for the data in the lpAttributeList buffer and call the function
again to initialize the buffer.
When you have finished using the list, call the DeleteProcThreadAttributeList function.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
DeleteProcThreadAttributeList
UpdateProcThreadAttribute
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL IsProcessCritical(
[in] HANDLE hProcess,
[out] PBOOL Critical
);
Parameters
[in] hProcess
A handle to the process to query. The process must have been opened with
PROCESS_QUERY_LIMITED_INFORMATION access.
[out] Critical
A pointer to the BOOL value this function will use to indicate whether the process is
considered critical.
Return value
This routine returns FALSE on failure. Any other value indicates success. Call GetLastError
to query for the specific error reason on failure.
Requirements
Header processthreadsapi.h
Library Kernel32.lib
DLL kernel32.dll
See also
HRESULT_FROM_WIN32
Feedback
Was this page helpful? ツ Yes ト No
Specifies the memory priority for a thread or process. This structure is used by the
GetProcessInformation, SetProcessInformation, GetThreadInformation, and
SetThreadInformation functions.
Syntax
C++
Members
MemoryPriority
The memory priority for the thread or process. This member can be one of the following
values.
Value Meaning
Remarks
The memory priority of a thread or process serves as a hint to the memory manager
when it trims pages from the working set. Other factors being equal, pages with lower
memory priority are trimmed before pages with higher memory priority. For more
information, see Working Set.
Requirements
See also
GetProcessInformation
GetThreadInformation
SetProcessInformation
SetThreadInformation
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
HANDLE OpenProcess(
[in] DWORD dwDesiredAccess,
[in] BOOL bInheritHandle,
[in] DWORD dwProcessId
);
Parameters
[in] dwDesiredAccess
The access to the process object. This access right is checked against the security
descriptor for the process. This parameter can be one or more of the process access
rights.
If the caller has enabled the SeDebugPrivilege privilege, the requested access is granted
regardless of the contents of the security descriptor.
[in] bInheritHandle
If this value is TRUE, processes created by this process will inherit the handle. Otherwise,
the processes do not inherit this handle.
[in] dwProcessId
If the specified process is the System Idle Process (0x00000000), the function fails and
the last error code is ERROR_INVALID_PARAMETER . If the specified process is the System
process or one of the Client Server Run-Time Subsystem (CSRSS) processes, this
function fails and the last error code is ERROR_ACCESS_DENIED because their access
restrictions prevent user-level code from opening them.
If you are using GetCurrentProcessId as an argument to this function, consider using
GetCurrentProcess instead of OpenProcess, for improved performance.
Return value
If the function succeeds, the return value is an open handle to the specified process.
If the function fails, the return value is NULL. To get extended error information, call
GetLastError.
Remarks
To open a handle to another local process and obtain full access rights, you must enable
the SeDebugPrivilege privilege. For more information, see Changing Privileges in a
Token.
The handle returned by the OpenProcess function can be used in any function that
requires a handle to a process, such as the wait functions, provided the appropriate
access rights were requested.
When you are finished with the handle, be sure to close it using the CloseHandle
function.
Examples
For an example, see Taking a Snapshot and Viewing Processes.
Requirements
Target Windows
Platform
Header processthreadsapi.h (include Windows.h on Windows Server 2003,
Windows Vista, Windows 7, Windows Server 2008 Windows Server 2008 R2)
Library Kernel32.lib
DLL Kernel32.dll
See also
AssignProcessToJobObject
CloseHandle
CreateProcess
CreateRemoteThread
DuplicateHandle
GetCurrentProcess
GetCurrentProcessId
GetExitCodeProcess
GetModuleFileNameEx
GetPriorityClass
Processes
ReadProcessMemory
SetPriorityClass
SetProcessWorkingSetSize
TerminateProcess
VirtualProtectEx
WriteProcessMemory
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
HANDLE OpenThread(
[in] DWORD dwDesiredAccess,
[in] BOOL bInheritHandle,
[in] DWORD dwThreadId
);
Parameters
[in] dwDesiredAccess
The access to the thread object. This access right is checked against the security
descriptor for the thread. This parameter can be one or more of the thread access rights.
If the caller has enabled the SeDebugPrivilege privilege, the requested access is granted
regardless of the contents of the security descriptor.
[in] bInheritHandle
If this value is TRUE, processes created by this process will inherit the handle. Otherwise,
the processes do not inherit this handle.
[in] dwThreadId
Return value
If the function succeeds, the return value is an open handle to the specified thread.
If the function fails, the return value is NULL. To get extended error information, call
GetLastError.
Remarks
The handle returned by OpenThread can be used in any function that requires a handle
to a thread, such as the wait functions, provided you requested the appropriate access
rights. The handle is granted access to the thread object only to the extent it was
specified in the dwDesiredAccess parameter.
When you are finished with the handle, be sure to close it by using the CloseHandle
function.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
CloseHandle
GetExitCodeThread
GetThreadContext
ResumeThread
SetThreadContext
SetTokenInformation
SuspendThread
TerminateThread
Threads
Feedback
Was this page helpful? ツ Yes ト No
Contains information about a newly created process and its primary thread. It is used
with the CreateProcess, CreateProcessAsUser, CreateProcessWithLogonW, or
CreateProcessWithTokenW function.
Syntax
C++
Members
hProcess
A handle to the newly created process. The handle is used to specify the process in all
functions that perform operations on the process object.
hThread
A handle to the primary thread of the newly created process. The handle is used to
specify the thread in all functions that perform operations on the thread object.
dwProcessId
A value that can be used to identify a process. The value is valid from the time the
process is created until all handles to the process are closed and the process object is
freed; at this point, the identifier may be reused.
dwThreadId
A value that can be used to identify a thread. The value is valid from the time the thread
is created until all handles to the thread are closed and the thread object is freed; at this
point, the identifier may be reused.
Remarks
If the function succeeds, be sure to call the CloseHandle function to close the hProcess
and hThread handles when you are finished with them. Otherwise, when the child
process exits, the system cannot clean up the process structures for the child process
because the parent process still has open handles to the child process. However, the
system will close these handles when the parent process terminates, so the structures
related to the child process object would be cleaned up at this point.
Examples
For an example, see Creating Processes.
Requirements
See also
CreateProcess
CreateProcessAsUser
CreateProcessWithLogonW
CreateProcessWithTokenW
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
Members
Flags
Value Meaning
Reserved
Requirements
Header processthreadsapi.h
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
Members
Version
Reserved
Reserved.
Type
Type of failure.
Value
Function Setting
Enable PME_FAILFAST_ON_COMMIT_FAIL_ENABLE
Disable PME_FAILFAST_ON_COMMIT_FAIL_DISABLE
Requirements
Minimum supported client Windows 10, version 1511 [desktop apps | UWP apps]
Minimum supported server Windows Server 2016 [desktop apps | UWP apps]
See also
PROCESS_INFORMATION_CLASS
PROCESS_MEMORY_EXHAUSTION_TYPE
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
Constants
PMETypeFailFastOnCommitFailure
Anytime memory management fails an allocation due to an inability to commit memory, it will
cause the process to trigger a Windows Error Reporting report and then terminate immediately
with STATUS_COMMITMENT_LIMIT.
The failure cannot be caught and handled by the app.
PMETypeMax
The maximum value for this enumeration. This value may change in a future version.
Requirements
Minimum supported client Windows 10, version 1511 [desktop apps | UWP apps]
Minimum supported server Windows Server 2016 [desktop apps | UWP apps]
Feedback
Was this page helpful? ツ Yes ト No
Specifies the throttling policies and how to apply them to a target process when that
process is subject to power management. This structure is used by the
SetProcessInformation function.
Syntax
C++
Members
Version
Value Meaning
ControlMask
This field enables the caller to take control of the power throttling mechanism.
Value Meaning
StateMask
Value Meaning
PROCESS_POWER_THROTTLING_EXECUTION_SPEED Manages the execution speed of the
process.
Requirements
Header processthreadsapi.h
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
Members
ProtectionLevel
Value Meaning
Header processthreadsapi.h
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL QueryProcessAffinityUpdateMode(
[in] HANDLE hProcess,
[out, optional] LPDWORD lpdwFlags
);
Parameters
[in] hProcess
The affinity update mode. This parameter can be one of the following values.
Value Meaning
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
To compile an application that calls this function, define _WIN32_WINNT as 0x0600 or
later. For more information, see Using the Windows Headers.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
SetProcessAffinityUpdateMode
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL QueryProtectedPolicy(
[in] LPCGUID PolicyGuid,
[out] PULONG_PTR PolicyValue
);
Parameters
[in] PolicyGuid
[out] PolicyValue
Return value
True if the function succeeds; otherwise, false.
Remarks
Protected policies are process-wide configuration settings that are stored in read-only
memory. This is intended to help protect the policy from being corrupted or altered in
an unintended way while an application is executing.
This function became available in Windows 8.1 and Windows Server 2012 R2 update 3
(the November 2014 update).
Requirements
Library Kernel32.lib
DLL Kernel32.dll
Feedback
Was this page helpful? ツ Yes ト No
Specifies the modifier flags for user-mode asynchronous procedure call (APC) objects.
Syntax
C++
Constants
QUEUE_USER_APC_FLAGS_NONE
No flags are passed. Behavior is identical to QueueUserAPC function.
QUEUE_USER_APC_FLAGS_SPECIAL_USER_APC
Queue a special user-mode APC instead of a regular user-mode APC.
QUEUE_USER_APC_CALLBACK_DATA_CONTEXT
Receive the processor context that was interrupted when the thread was directed to call the APC
function.
Remarks
The Parameter argument of the PAPCFUNC callback function is modified to point to an
APC_CALLBACK_DATA structure (see below), which contains the original Parameter
argument, a pointer to the interrupted processor context, and reserved fields.
C++
Requirements
See also
QueueUserAPC2
Feedback
Was this page helpful? ツ Yes ト No
Adds a user-mode asynchronous procedure call (APC) object to the APC queue of the
specified thread.
Syntax
C++
DWORD QueueUserAPC(
[in] PAPCFUNC pfnAPC,
[in] HANDLE hThread,
[in] ULONG_PTR dwData
);
Parameters
[in] pfnAPC
[in] hThread
A handle to the thread. The handle must have the THREAD_SET_CONTEXT access right.
For more information, see Synchronization Object Security and Access Rights.
[in] dwData
A single value that is passed to the APC function pointed to by the pfnAPC parameter.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError. Windows Server 2003 and Windows XP: There are no error values defined
for this function that can be retrieved by calling GetLastError.
Remarks
See QueueUserAPC2 function for information on special user-mode APCs.
The APC support provided in the operating system allows an application to queue an
APC object to a thread. To ensure successful execution of functions used by the APC,
APCs should be queued only to threads in the caller's process.
7 Note
Queuing APCs to threads outside the caller's process is not recommended for a
number of reasons. DLL rebasing can cause the addresses of functions used by the
APC to be incorrect when the functions are executed outside the caller's process.
Similarly, if a 64-bit process queues an APC to a 32-bit process or vice versa,
addresses will be incorrect and the application will crash. Other factors can prevent
successful function execution, even if the address is known.
Each thread has its own APC queue. The queuing of an APC is a request for the thread
to call the APC function. The operating system issues a software interrupt to direct the
thread to call the APC function.
When a user-mode APC is queued, the thread is not directed to call the APC function
unless it is in an alertable state. After the thread is in an alertable state, the thread
handles all pending APCs in first in, first out (FIFO) order, and the wait operation returns
WAIT_IO_COMPLETION. A thread enters an alertable state by using SleepEx function,
SignalObjectAndWait function, WaitForSingleObjectEx function,
WaitForMultipleObjectsEx function, or MsgWaitForMultipleObjectsEx function.
If an application queues an APC before the thread begins running, the thread begins by
calling the APC function. After the thread calls an APC function, it calls the APC functions
for all APCs in its APC queue.
It is possible to sleep or wait for an object within the APC. If you perform an alertable
wait inside an APC, it will recursively dispatch the APCs. This can cause a stack overflow.
When the thread is in the process of being terminated, calling QueueUserAPC to add to
the thread's APC queue will fail with (31) ERROR_GEN_FAILURE.
Note that the ReadFileEx function, SetWaitableTimer function, and WriteFileEx function
functions are implemented using an APC as the completion notification callback
mechanism.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
PAPCFUNC callback function
Asynchronous Procedure Calls
Synchronization Functions
Feedback
Was this page helpful? ツ Yes ト No
Adds a user-mode asynchronous procedure call (APC) object to the APC queue of the
specified thread.
Syntax
C++
BOOL QueueUserAPC2(
PAPCFUNC ApcRoutine,
HANDLE Thread,
ULONG_PTR Data,
QUEUE_USER_APC_FLAGS Flags
);
Parameters
ApcRoutine
For special user-mode APCs, an alertable wait is not required. See Remarks for more
information about special user-mode APCs.
Thread
Data
A single value that is passed to the APC function pointed to by the ApcRoutine
parameter.
Flags
A value from QUEUE_USER_APC_FLAGS enumeration that modifies the behavior of the
user-mode APC.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
Regular user-mode APCs are only executed if the target thread is in an alertable state.
See QueueUserAPC function for additional remarks on regular user-mode APCs.
Special user-mode APCs always execute, even if the target thread is not in an alertable
state. For example, if the target thread is currently executing user-mode code, or if the
target thread is currently performing an alertable wait, the target thread will be
interrupted immediately for APC execution. If the target thread is executing a system
call, or performing a non-alertable wait, the APC will be executed after the system call or
non-alertable wait finishes (the wait is not interrupted).
Since the execution of the special user-mode APC is not synchronized with the target
thread, particular care must be taken (beyond the normal requirements for
multithreading and synchronization). For example, when acquiring any locks, the
interrupted target thread may already own the lock or be in the process of acquiring or
releasing the lock. In addition, because there are no facilities to block a thread from
receiving special user-mode APCs, a special user-mode APC can be executed on a target
thread that is already executing a special user-mode APC.
Currently, special user-mode APCs are only supported on native architectures, and not
when running under WoW.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
Feedback
Was this page helpful? ツ Yes ト No
Decrements a thread's suspend count. When the suspend count is decremented to zero,
the execution of the thread is resumed.
Syntax
C++
DWORD ResumeThread(
[in] HANDLE hThread
);
Parameters
[in] hThread
This handle must have the THREAD_SUSPEND_RESUME access right. For more
information, see Thread Security and Access Rights.
Return value
If the function succeeds, the return value is the thread's previous suspend count.
If the function fails, the return value is (DWORD) -1. To get extended error information,
call GetLastError.
Remarks
The ResumeThread function checks the suspend count of the subject thread. If the
suspend count is zero, the thread is not currently suspended. Otherwise, the subject
thread's suspend count is decremented. If the resulting value is zero, then the execution
of the subject thread is resumed.
If the return value is zero, the specified thread was not suspended. If the return value is
1, the specified thread was suspended but was restarted. If the return value is greater
than 1, the specified thread is still suspended.
Note that while reporting debug events, all threads within the reporting process are
frozen. Debuggers are expected to use the SuspendThread and ResumeThread
functions to limit the set of threads that can execute within a process. By suspending all
threads in a process except for the one reporting a debug event, it is possible to "single
step" a single thread. The other threads are not released by a continue operation if they
are suspended.
Windows Phone 8.1: This function is supported for Windows Phone Store apps on
Windows Phone 8.1 and later.
Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows
Store apps on Windows 8.1, Windows Server 2012 R2, and later.
Requirements
Target Windows
Platform
See also
OpenThread
Threads
Feedback
Was this page helpful? ツ Yes ト No
Sets the priority class for the specified process. This value together with the priority
value of each thread of the process determines each thread's base priority level.
Syntax
C++
BOOL SetPriorityClass(
[in] HANDLE hProcess,
[in] DWORD dwPriorityClass
);
Parameters
[in] hProcess
The handle must have the PROCESS_SET_INFORMATION access right. For more
information, see Process Security and Access Rights.
[in] dwPriorityClass
The priority class for the process. This parameter can be one of the following values.
Priority Meaning
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
Every thread has a base priority level determined by the thread's priority value and the
priority class of its process. The system uses the base priority level of all executable
threads to determine which thread gets the next slice of CPU time. The SetThreadPriority
function enables setting the base priority level of a thread relative to the priority class of
its process. For more information, see Scheduling Priorities.
The *_PRIORITY_CLASS values affect the CPU scheduling priority of the process. For
processes that perform background work such as file I/O, network I/O, or data
processing, it is not sufficient to adjust the CPU scheduling priority; even an idle CPU
priority process can easily interfere with system responsiveness when it uses the disk
and memory. Processes that perform background work should use the
PROCESS_MODE_BACKGROUND_BEGIN and PROCESS_MODE_BACKGROUND_END
values to adjust their resource scheduling priorities; processes that interact with the user
should not use PROCESS_MODE_BACKGROUND_BEGIN.
If a process is in background processing mode, the new threads it creates will also be in
background processing mode. When a thread is in background processing mode, it
should minimize sharing resources such as critical sections, heaps, and handles with
other threads in the process, otherwise priority inversions can occur. If there are threads
executing at high priority, a thread in background processing mode may not be
scheduled promptly, but it will never be starved.
Examples
The following example demonstrates the use of process background mode.
C++
#include <windows.h>
#include <tchar.h>
int main( void )
{
DWORD dwError, dwPriClass;
if(!SetPriorityClass(GetCurrentProcess(), PROCESS_MODE_BACKGROUND_BEGIN))
{
dwError = GetLastError();
if( ERROR_PROCESS_MODE_ALREADY_BACKGROUND == dwError)
_tprintf(TEXT("Already in background mode\n"));
else _tprintf(TEXT("Failed to enter background mode (%d)\n"),
dwError);
goto Cleanup;
}
dwPriClass = GetPriorityClass(GetCurrentProcess());
//
// Perform background work
//
;
if(!SetPriorityClass(GetCurrentProcess(), PROCESS_MODE_BACKGROUND_END))
{
_tprintf(TEXT("Failed to end background mode (%d)\n"),
GetLastError());
}
Cleanup:
// Clean up
;
return 0;
}
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
CreateProcess
CreateThread
GetPriorityClass
GetThreadPriority
Processes
Scheduling Priorities
SetThreadPriority
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL SetProcessAffinityUpdateMode(
[in] HANDLE hProcess,
[in] DWORD dwFlags
);
Parameters
[in] hProcess
[in] dwFlags
The affinity update mode. This parameter can be one of the following values.
Value Meaning
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
The system can adjust process affinity under various conditions, such as when a
processor is added dynamically. By default, dynamic updates to the process affinity are
disabled for each process.
Processes should use this function to indicate whether they can handle dynamic
adjustment of process affinity by the system. After a process enables affinity update
mode, it can call this function to disable it. However, a process cannot enable affinity
update mode after it has used this function to disable it.
Child processes do not inherit the affinity update mode of the parent process. The
affinity update mode must be explicitly set for each child process.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
QueryProcessAffinityUpdateMode
Feedback
ツY トN
ツ Yes ト No
Was this page helpful?
7 Note
This API was added to the 19041 SDK in an update released in November 2020.
Syntax
C++
BOOL SetProcessDynamicEnforcedCetCompatibleRanges(
HANDLE Process,
USHORT NumberOfRanges,
PPROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE Ranges
);
Parameters
Process
NumberOfRanges
Ranges
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError. Note that even if the function fails, a portion of the supplied CETCOMPAT
ranges may have been successfully processed. The caller needs to check the flags in
each individual CETCOMPAT range specified via Ranges to determine if it was
successfully processed.
Remarks
User-mode Hardware-enforced Stack Protection (HSP) is a security feature where the
CPU verifies function return addresses at runtime by employing a shadow stack
mechanism, if supported by the hardware. In HSP compatibility mode, only shadow
stack violations occurring in modules that are considered compatible with shadow
stacks (CETCOMPAT) are fatal. For a module to be considered CETCOMPAT, it needs to
be either compiled with CETCOMPAT for binaries, or marked using
SetProcessDynamicEnforcedCetCompatibleRanges for dynamic code. In HSP strict mode,
all shadow stack violations are fatal.
Requirements
Minimum supported client Windows 10, version 2004 (10.0; Build 19041.662)
Minimum supported server Windows Server, version 2004 (10.0; Build 19041.662)
Header processthreadsapi.h
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL SetProcessInformation(
[in] HANDLE hProcess,
[in] PROCESS_INFORMATION_CLASS ProcessInformationClass,
LPVOID ProcessInformation,
[in] DWORD ProcessInformationSize
);
Parameters
[in] hProcess
[in] ProcessInformationClass
ProcessInformation
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
To help improve system performance, applications should use the
SetProcessInformation function with ProcessMemoryPriority to lower the default
memory priority of threads that perform background operations or access files and data
that are not expected to be accessed again soon. For example, a file indexing
application might set a lower default priority for the process that performs the indexing
task.
Memory priority helps to determine how long pages remain in the working set of a
process before they are trimmed. A process's memory priority determines the default
priority of the physical pages that are added to the process working set by the threads
of that process. When the memory manager trims the working set, it trims lower priority
pages before higher priority pages. This improves overall system performance because
higher priority pages are less likely to be trimmed from the working set and then trigger
a page fault when they are accessed again.
Examples
The following example shows how to call SetProcessInformation with
ProcessMemoryPriority to set low memory priority as the default for the calling
process.
syntax
DWORD ErrorCode;
BOOL Success;
MEMORY_PRIORITY_INFORMATION MemPrio;
//
// Set low memory priority on the current process.
//
ZeroMemory(&MemPrio, sizeof(MemPrio));
MemPrio.MemoryPriority = MEMORY_PRIORITY_LOW;
Success = SetProcessInformation(GetCurrentProcess(),
ProcessMemoryPriority,
&MemPrio,
sizeof(MemPrio));
if (!Success) {
ErrorCode = GetLastError();
fprintf(stderr, "Set process memory priority failed: %d\n",
ErrorCode);
goto cleanup;
}
syntax
PROCESS_POWER_THROTTLING_STATE PowerThrottling;
RtlZeroMemory(&PowerThrottling, sizeof(PowerThrottling));
PowerThrottling.Version = PROCESS_POWER_THROTTLING_CURRENT_VERSION;
//
// EcoQoS
// Turn EXECUTION_SPEED throttling on.
// ControlMask selects the mechanism and StateMask declares which mechanism
should be on or off.
//
PowerThrottling.ControlMask = PROCESS_POWER_THROTTLING_EXECUTION_SPEED;
PowerThrottling.StateMask = PROCESS_POWER_THROTTLING_EXECUTION_SPEED;
SetProcessInformation(GetCurrentProcess(),
ProcessPowerThrottling,
&PowerThrottling,
sizeof(PowerThrottling));
//
// HighQoS
// Turn EXECUTION_SPEED throttling off.
// ControlMask selects the mechanism and StateMask is set to zero as
mechanisms should be turned off.
//
PowerThrottling.ControlMask = PROCESS_POWER_THROTTLING_EXECUTION_SPEED;
PowerThrottling.StateMask = 0;
SetProcessInformation(GetCurrentProcess(),
ProcessPowerThrottling,
&PowerThrottling,
sizeof(PowerThrottling));
PROCESS_POWER_THROTTLING_STATE PowerThrottling;
RtlZeroMemory(&PowerThrottling, sizeof(PowerThrottling));
PowerThrottling.Version = PROCESS_POWER_THROTTLING_CURRENT_VERSION;
//
// Ignore Timer Resolution Requests.
// Turn IGNORE_TIMER_RESOLUTION throttling on.
// ControlMask selects the mechanism and StateMask declares which mechanism
should be on or off.
//
PowerThrottling.ControlMask =
PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION;
PowerThrottling.StateMask =
PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION;
SetProcessInformation(GetCurrentProcess(),
ProcessPowerThrottling,
&PowerThrottling,
sizeof(PowerThrottling));
//
// Always honor Timer Resolution Requests.
// Turn IGNORE_TIMER_RESOLUTION throttling off.
// ControlMask selects the mechanism and StateMask is set to zero as
mechanisms should be turned off.
//
PowerThrottling.ControlMask =
PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION;
PowerThrottling.StateMask = 0;
SetProcessInformation(GetCurrentProcess(),
ProcessPowerThrottling,
&PowerThrottling,
sizeof(PowerThrottling));
syntax
PROCESS_POWER_THROTTLING_STATE PowerThrottling;
RtlZeroMemory(&PowerThrottling, sizeof(PowerThrottling));
PowerThrottling.Version = PROCESS_POWER_THROTTLING_CURRENT_VERSION;
//
// Let system manage all power throttling. ControlMask is set to 0 as we
don’t want
// to control any mechanisms.
//
PowerThrottling.ControlMask = 0;
PowerThrottling.StateMask = 0;
SetProcessInformation(GetCurrentProcess(),
ProcessPowerThrottling,
&PowerThrottling,
sizeof(PowerThrottling));
Requirements
Minimum supported server Windows Server 2012 [desktop apps | UWP apps]
Library Kernel32.lib
DLL Kernel32.dll
See also
GetProcessInformation
MEMORY_PRIORITY_INFORMATION
PROCESS_INFORMATION_CLASS
SetThreadInformation
Feedback
Was this page helpful? ツ Yes ト No
Sets a mitigation policy for the calling process. Mitigation policies enable a process to
harden itself against various types of attacks.
Syntax
C++
BOOL SetProcessMitigationPolicy(
[in] PROCESS_MITIGATION_POLICY MitigationPolicy,
[in] PVOID lpBuffer,
[in] SIZE_T dwLength
);
Parameters
[in] MitigationPolicy
The mitigation policy to apply. This parameter can be one of the following values.
Value Meaning
ProcessDynamicCodePolicy The dynamic code policy of the process. When turned on,
the process cannot generate dynamic code or modify
existing executable code.
The lpBuffer parameter points to a
PROCESS_MITIGATION_DYNAMIC_CODE_POLICY structure
that specifies the dynamic code policy flags.
Value Meaning
ProcessMitigationOptionsMask Returns the mask of valid bits for all the mitigation options
on the system. An application can set many mitigation
options without querying the operating system for
mitigation options by combining bitwise with the mask to
exclude all non-supported bits at once.
The lpBuffer parameter points to a ULONG64 bit vector for
the mask, or to accommodate more than 64 bits, a two-
element array of ULONG64 bit vectors.
ProcessFontDisablePolicy The policy regarding font loading for the process. When
turned on, the process cannot load non-system fonts.
The lpBuffer parameter points to a
PROCESS_MITIGATION_FONT_DISABLE_POLICY structure
that specifies the policy flags for font loading.
Value Meaning
ProcessImageLoadPolicy The policy regarding image loading for the process, which
determines the types of executable images that are allowed
to be mapped into the process. When turned on, images
cannot be loaded from some locations, such a remote
devices or files that have the low mandatory label.
The lpBuffer parameter points to a
PROCESS_MITIGATION_IMAGE_LOAD_POLICY structure that
specifies the policy flags for image loading.
ProcessSideChannelIsolationPolicy Windows 10, version 1809 and above: The policy regarding
isolation of side channels for the specified process.
The lpBuffer parameter points to a
PROCESS_MITIGATION_SIDE_CHANNEL_ISOLATION_POLICY
structure that specifies the policy flags for side channel
isolation.
ProcessUserShadowStackPolicy Windows 10, version 2004 and above: The policy regarding
user-mode Hardware-enforced Stack Protection for the
process.
The lpBuffer parameter points to a
PROCESS_MITIGATION_USER_SHADOW_STACK_POLICY
structure that specifies the policy flags for user-mode
Hardware-enforced Stack Protection.
[in] lpBuffer
[in] dwLength
Return value
If the function succeeds, it returns TRUE. If the function fails, it returns FALSE. To retrieve
error values defined for this function, call GetLastError.
Remarks
Setting mitigation policy for a process helps prevent an attacker from exploiting security
vulnerabilities. Use the SetProcessMitigationPolicy function to enable or disable security
mitigation programmatically.
ASLR mitigation policies cannot be made less restrictive after they have been applied.
To compile an application that uses this function, set _WIN32_WINNT >= 0x0602. For
more information, see Using the Windows Headers.
Requirements
Header processthreadsapi.h
Library Kernel32.lib
DLL Kernel32.dll
Feedback
Was this page helpful? ツ Yes ト No
Disables or enables the ability of the system to temporarily boost the priority of the
threads of the specified process.
Syntax
C++
BOOL SetProcessPriorityBoost(
[in] HANDLE hProcess,
[in] BOOL bDisablePriorityBoost
);
Parameters
[in] hProcess
A handle to the process. This handle must have the PROCESS_SET_INFORMATION access
right. For more information, see Process Security and Access Rights.
[in] bDisablePriorityBoost
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
When a thread is running in one of the dynamic priority classes, the system temporarily
boosts the thread's priority when it is taken out of a wait state. If
SetProcessPriorityBoost is called with the DisablePriorityBoost parameter set to TRUE,
its threads' priorities are not boosted. This setting affects all existing threads and any
threads subsequently created by the process. To restore normal behavior, call
SetProcessPriorityBoost with DisablePriorityBoost set to FALSE.
Requirements
Minimum supported server Windows Server 2003 [desktop apps | UWP apps]
Library Kernel32.lib
DLL Kernel32.dll
See also
GetProcessPriorityBoost
Priority Boosts
Processes
Scheduling Priorities
Feedback
Was this page helpful? ツ Yes ト No
Sets shutdown parameters for the currently calling process. This function sets a
shutdown order for a process relative to the other processes in the system.
Syntax
C++
BOOL SetProcessShutdownParameters(
[in] DWORD dwLevel,
[in] DWORD dwFlags
);
Parameters
[in] dwLevel
The shutdown priority for a process relative to other processes in the system. The
system shuts down processes from high dwLevel values to low. The highest and lowest
shutdown priorities are reserved for system components. This parameter must be in the
following range of values.
Value Meaning
[in] dwFlags
This parameter can be the following value.
Value Meaning
Return value
If the function is succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
Applications running in the system security context do not get shut down by the
operating system. They get notified of shutdown or logoff through the callback function
installable via SetConsoleCtrlHandler. They also get notified in the order specified by the
dwLevel parameter.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
GetProcessShutdownParameters
Processes
SetConsoleCtrlHandler
Feedback
Was this page helpful? ツ Yes ト No
Sets a protected policy. This function is for use primarily by Windows, and not designed
for external use.
Syntax
C++
BOOL SetProtectedPolicy(
[in] LPCGUID PolicyGuid,
[in] ULONG_PTR PolicyValue,
[out] PULONG_PTR OldPolicyValue
);
Parameters
[in] PolicyGuid
[in] PolicyValue
[out] OldPolicyValue
Optionally receives the original value that was associated with the supplied policy.
Return value
True if the function succeeds; otherwise, false. To retrieve error values for this function,
call GetLastError.
Remarks
Protected policies are process-wide configuration settings that are stored in read-only
memory. This is intended to help protect the policy from being corrupted or altered in
an unintended way while an application is executing. Protected policies are primarily a
construct internal to Windows.
This function became available in update 3 (the November 2014 update) for
Windows 8.1 and Windows Server 2012 R2.
Requirements
Library Kernel32.lib
DLL Kernel32.dll
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
HRESULT SetThreadDescription(
[in] HANDLE hThread,
[in] PCWSTR lpThreadDescription
);
Parameters
[in] hThread
A handle for the thread for which you want to set the description. The handle must have
THREAD_SET_LIMITED_INFORMATION access.
[in] lpThreadDescription
Return value
If the function succeeds, the return value is the HRESULT that denotes a successful
operation. If the function fails, the return value is an HRESULT that denotes the error.
Remarks
The description of a thread can be set more than once; the most recently set value is
used. You can retrieve the description of a thread by calling GetThreadDescription.
Windows Server 2016, Windows 10 LTSB 2016 and Windows 10 version 1607:
SetThreadDescription is only available by Run Time Dynamic Linking in KernelBase.dll.
Examples
The following example sets the description for the current thread to simulation_thread .
C++
Requirements
Minimum supported client Windows 10, version 1607 [desktop apps | UWP apps]
Minimum supported server Windows Server 2016 [desktop apps | UWP apps]
Header processthreadsapi.h
Library Kernel32.lib
DLL Kernel32.dll
See also
GetThreadDescription, How to: Set a Thread Name in Native Code
Feedback
Was this page helpful? ツ Yes ト No
Sets a preferred processor for a thread. The system schedules threads on their preferred
processors whenever possible.
On a system with more than 64 processors, this function sets the preferred processor to
a logical processor in the processor group to which the calling thread is assigned. Use
the SetThreadIdealProcessorEx function to specify a processor group and preferred
processor.
Syntax
C++
DWORD SetThreadIdealProcessor(
[in] HANDLE hThread,
[in] DWORD dwIdealProcessor
);
Parameters
[in] hThread
A handle to the thread whose preferred processor is to be set. The handle must have the
THREAD_SET_INFORMATION access right. For more information, see Thread Security
and Access Rights.
[in] dwIdealProcessor
The number of the preferred processor for the thread. This value is zero-based. If this
parameter is MAXIMUM_PROCESSORS, the function returns the current ideal processor
without changing it.
Return value
If the function succeeds, the return value is the previous preferred processor.
If the function fails, the return value is (DWORD) – 1. To get extended error information,
call GetLastError.
Remarks
You can use the GetSystemInfo function to determine the number of processors on the
computer. You can also use the GetProcessAffinityMask function to check the processors
on which the thread is allowed to run. Note that GetProcessAffinityMask returns a
bitmask whereas SetThreadIdealProcessor uses an integer value to represent the
processor.
Starting with Windows 11 and Windows Server 2022, on a system with more than 64
processors, process and thread affinities span all processors in the system, across all
processor groups, by default. The SetThreadIdealProcessor function sets the preferred
processor to a logical processor in the thread's primary group.
Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows
Store apps on Windows 8.1, Windows Server 2012 R2, and later.
Requirements
Minimum supported server Windows Server 2003 [desktop apps | UWP apps]
Library Kernel32.lib
DLL Kernel32.dll
See also
GetProcessAffinityMask
GetSystemInfo
Multiple Processors
OpenThread
SetThreadAffinityMask
SetThreadIdealProcessorEx
Threads
Feedback
Was this page helpful? ツ Yes ト No
Sets the ideal processor for the specified thread and optionally retrieves the previous
ideal processor.
Syntax
C++
BOOL SetThreadIdealProcessorEx(
[in] HANDLE hThread,
[in] PPROCESSOR_NUMBER lpIdealProcessor,
[out, optional] PPROCESSOR_NUMBER lpPreviousIdealProcessor
);
Parameters
[in] hThread
A handle to the thread for which to set the ideal processor. This handle must have been
created with the THREAD_SET_INFORMATION access right. For more information, see
Thread Security and Access Rights.
[in] lpIdealProcessor
Return value
If the function succeeds, it returns a nonzero value.
If the function fails, it returns zero. To get extended error information, use GetLastError.
Remarks
Specifying a thread ideal processor provides a hint to the scheduler about the preferred
processor for a thread. The scheduler runs the thread on the thread's ideal processor
when possible.
Starting with Windows 11 and Windows Server 2022, on a system with more than 64
processors, process and thread affinities span all processors in the system, across all
processor groups, by default. The SetThreadIdealProcessorEx, in setting the preferred
processor, also sets the thread's primary group to the group of the preferred processor.
To compile an application that uses this function, set _WIN32_WINNT >= 0x0601. For
more information, see Using the Windows Headers.
Windows Phone 8.1: This function is supported for Windows Phone Store apps on
Windows Phone 8.1 and later.
Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows
Store apps on Windows 8.1, Windows Server 2012 R2, and later.
Requirements
Minimum supported server Windows Server 2008 R2 [desktop apps | UWP apps]
See also
GetThreadIdealProcessorEx
SetThreadIdealProcessor
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL SetThreadInformation(
[in] HANDLE hThread,
[in] THREAD_INFORMATION_CLASS ThreadInformationClass,
LPVOID ThreadInformation,
[in] DWORD ThreadInformationSize
);
Parameters
[in] hThread
A handle to the thread. The handle must have THREAD_SET_INFORMATION access right.
For more information, see Thread Security and Access Rights.
[in] ThreadInformationClass
The class of information to set. The only supported values are ThreadMemoryPriority
and ThreadPowerThrottling.
ThreadInformation
[in] ThreadInformationSize
The size in bytes of the structure specified by the ThreadInformation parameter.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
To help improve system performance, applications should use the
SetThreadInformation function with ThreadMemoryPriority to lower the memory
priority of threads that perform background operations or access files and data that are
not expected to be accessed again soon. For example, an anti-malware application
might lower the priority of threads involved in scanning files.
Memory priority helps to determine how long pages remain in the working set of a
process before they are trimmed. A thread's memory priority determines the minimum
priority of the physical pages that are added to the process working set by that thread.
When the memory manager trims the working set, it trims lower priority pages before
higher priority pages. This improves overall system performance because higher priority
pages are less likely to be trimmed from the working set and then trigger a page fault
when they are accessed again.
automatically infer a Quality of Service level. For more information, see Quality of
Service.
Examples
The following example shows how to call SetThreadInformation with
ThreadMemoryPriority to set low memory priority on the current thread.
DWORD ErrorCode;
BOOL Success;
MEMORY_PRIORITY_INFORMATION MemPrio;
//
// Set low memory priority on the current thread.
//
ZeroMemory(&MemPrio, sizeof(MemPrio));
MemPrio.MemoryPriority = MEMORY_PRIORITY_LOW;
Success = SetThreadInformation(GetCurrentThread(),
ThreadMemoryPriority,
&MemPrio,
sizeof(MemPrio));
if (!Success) {
ErrorCode = GetLastError();
fprintf(stderr, "Set thread memory priority failed: %d\n", ErrorCode);
}
THREAD_POWER_THROTTLING_STATE PowerThrottling;
ZeroMemory(&PowerThrottling, sizeof(PowerThrottling));
PowerThrottling.Version = THREAD_POWER_THROTTLING_CURRENT_VERSION;
//
// EcoQoS
// Turn EXECUTION_SPEED throttling on.
// ControlMask selects the mechanism and StateMask declares which mechanism
should be on or off.
//
PowerThrottling.ControlMask = THREAD_POWER_THROTTLING_EXECUTION_SPEED;
PowerThrottling.StateMask = THREAD_POWER_THROTTLING_EXECUTION_SPEED;
SetThreadInformation(GetCurrentThread(),
ThreadPowerThrottling,
&PowerThrottling,
sizeof(PowerThrottling));
//
// HighQoS
// Turn EXECUTION_SPEED throttling off.
// ControlMask selects the mechanism and StateMask is set to zero as
mechanisms should be turned off.
//
PowerThrottling.ControlMask = THREAD_POWER_THROTTLING_EXECUTION_SPEED;
PowerThrottling.StateMask = 0;
SetThreadInformation(GetCurrentThread(),
ThreadPowerThrottling,
&PowerThrottling,
sizeof(PowerThrottling));
//
// Let system manage all power throttling. ControlMask is set to 0 as we
don’t want
// to control any mechanisms.
//
PowerThrottling.ControlMask = 0;
PowerThrottling.StateMask = 0;
SetThreadInformation(GetCurrentThread(),
ThreadPowerThrottling,
&PowerThrottling,
sizeof(PowerThrottling));
Requirements
Library Kernel32.lib
DLL Kernel32.dll
See also
GetThreadInformation
SetProcessInformation
Feedback
Was this page helpful? ツ Yes ト No
Disables or enables the ability of the system to temporarily boost the priority of a
thread.
Syntax
C++
BOOL SetThreadPriorityBoost(
[in] HANDLE hThread,
[in] BOOL bDisablePriorityBoost
);
Parameters
[in] hThread
A handle to the thread whose priority is to be boosted. The handle must have the
THREAD_SET_INFORMATION or THREAD_SET_LIMITED_INFORMATION access right.
For more information, see Thread Security and Access Rights.
Windows Server 2003 and Windows XP: The handle must have the
THREAD_SET_INFORMATION access right.
[in] bDisablePriorityBoost
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
When a thread is running in one of the dynamic priority classes, the system temporarily
boosts the thread's priority when it is taken out of a wait state. If
SetThreadPriorityBoost is called with the DisablePriorityBoost parameter set to TRUE,
the thread's priority is not boosted. To restore normal behavior, call
SetThreadPriorityBoost with DisablePriorityBoost set to FALSE.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
GetThreadPriorityBoost
OpenThread
Priority Boosts
Scheduling Priorities
Threads
Feedback
Was this page helpful? ツ Yes ト No
Sets the minimum size of the stack associated with the calling thread or fiber that will be
available during any stack overflow exceptions. This is useful for handling stack overflow
exceptions; the application can safely use the specified number of bytes during
exception handling.
Syntax
C++
BOOL SetThreadStackGuarantee(
[in, out] PULONG StackSizeInBytes
);
Parameters
[in, out] StackSizeInBytes
The size of the stack, in bytes. On return, this value is set to the size of the previous
stack, in bytes.
If this parameter is 0 (zero), the function succeeds and the parameter contains the size
of the current stack.
If the specified size is less than the current size, the function succeeds but ignores this
request. Therefore, you cannot use this function to reduce the size of the stack.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is 0 (zero). To get extended error information, call
GetLastError.
Remarks
If the function is successful, the application can handle possible
EXCEPTION_STACK_OVERFLOW exceptions using structured exception handling. To
resume execution after handling a stack overflow, you must perform certain recovery
steps. If you are using the Microsoft C/C++ compiler, call the _resetstkoflw function. If
you are using another compiler, see the documentation for the compiler for information
on recovering from stack overflows.
To set the stack guarantee for a fiber, you must first call the SwitchToFiber function to
execute the fiber. After you set the guarantee for this fiber, it is used by the fiber no
matter which thread executes the fiber.
Requirements
Minimum Windows Vista, Windows XP Professional x64 Edition [desktop apps only]
supported
client
Minimum Windows Server 2008, Windows Server 2003 with SP1 [desktop apps only]
supported
server
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
Process and Thread Functions
Threads
Feedback
Was this page helpful? ツ Yes ト No
Specifies the window station, desktop, standard handles, and appearance of the main
window for a process at creation time.
Syntax
C++
Members
cb
lpReserved
lpDesktop
The name of the desktop, or the name of both the desktop and window station for this
process. A backslash in the string indicates that the string includes both the desktop and
window station names.
lpTitle
For console processes, this is the title displayed in the title bar if a new console window
is created. If NULL, the name of the executable file is used as the window title instead.
This parameter must be NULL for GUI or console processes that do not create a new
console window.
dwX
If dwFlags specifies STARTF_USEPOSITION, this member is the x offset of the upper left
corner of a window if a new window is created, in pixels. Otherwise, this member is
ignored.
The offset is from the upper left corner of the screen. For GUI processes, the specified
position is used the first time the new process calls CreateWindow to create an
overlapped window if the x parameter of CreateWindow is CW_USEDEFAULT.
dwY
If dwFlags specifies STARTF_USEPOSITION, this member is the y offset of the upper left
corner of a window if a new window is created, in pixels. Otherwise, this member is
ignored.
The offset is from the upper left corner of the screen. For GUI processes, the specified
position is used the first time the new process calls CreateWindow to create an
overlapped window if the y parameter of CreateWindow is CW_USEDEFAULT.
dwXSize
If dwFlags specifies STARTF_USESIZE, this member is the width of the window if a new
window is created, in pixels. Otherwise, this member is ignored.
For GUI processes, this is used only the first time the new process calls CreateWindow to
create an overlapped window if the nWidth parameter of CreateWindow is
CW_USEDEFAULT.
dwYSize
If dwFlags specifies STARTF_USESIZE, this member is the height of the window if a new
window is created, in pixels. Otherwise, this member is ignored.
For GUI processes, this is used only the first time the new process calls CreateWindow to
create an overlapped window if the nHeight parameter of CreateWindow is
CW_USEDEFAULT.
dwXCountChars
dwYCountChars
dwFillAttribute
dwFlags
A bitfield that determines whether certain STARTUPINFO members are used when the
process creates a window. This member can be one or more of the following values.
Value Meaning
The system turns the feedback cursor off after the first
call to GetMessage, regardless of whether the process is
drawing.
STARTF_FORCEOFFFEEDBACK Indicates that the feedback cursor is forced off while the
0x00000080 process is starting. The Normal Select cursor is displayed.
STARTF_TITLEISLINKNAME The lpTitle member contains the path of the shortcut file
0x00000800 (.lnk) that the user invoked to start this process. This is
typically set by the shell when a .lnk file pointing to the
launched application is invoked. Most applications will
not need to set this value.
wShowWindow
For GUI processes, the first time ShowWindow is called, its nCmdShow parameter is
ignored wShowWindow specifies the default value. In subsequent calls to ShowWindow,
the wShowWindow member is used if the nCmdShow parameter of ShowWindow is set
to SW_SHOWDEFAULT.
cbReserved2
hStdInput
hStdOutput
If a process is launched from the taskbar or jump list, the system sets hStdOutput to a
handle to the monitor that contains the taskbar or jump list used to launch the process.
For more information, see Remarks.Windows 7, Windows Server 2008 R2,
Windows Vista, Windows Server 2008, Windows XP and Windows Server 2003: This
behavior was introduced in Windows 8 and Windows Server 2012.
hStdError
Remarks
For graphical user interface (GUI) processes, this information affects the first window
created by the CreateWindow function and shown by the ShowWindow function. For
console processes, this information affects the console window if a new console is
created for the process. A process can use the GetStartupInfo function to retrieve the
STARTUPINFO structure specified when the process was created.
If a GUI process is being started and neither STARTF_FORCEONFEEDBACK or
STARTF_FORCEOFFFEEDBACK is specified, the process feedback cursor is used. A GUI
process is one whose subsystem is specified as "windows."
If a process is launched from the taskbar or jump list, the system sets GetStartupInfo to
retrieve the STARTUPINFO structure and check that hStdOutput is set. If so, use
GetMonitorInfo to check whether hStdOutput is a valid monitor handle (HMONITOR).
The process can then use the handle to position its windows.
Examples
C++
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
if( argc != 2 )
{
printf("Usage: %s [cmdline]\n", argv[0]);
return;
}
7 Note
Requirements
See also
CreateProcess
CreateProcessAsUser
CreateProcessWithLogonW
CreateProcessWithTokenW
GetStartupInfo
Feedback
Was this page helpful? ツ Yes ト No
Specifies the window station, desktop, standard handles, and appearance of the main
window for a process at creation time.
Syntax
C++
Members
cb
lpReserved
lpDesktop
The name of the desktop, or the name of both the desktop and window station for this
process. A backslash in the string indicates that the string includes both the desktop and
window station names.
lpTitle
For console processes, this is the title displayed in the title bar if a new console window
is created. If NULL, the name of the executable file is used as the window title instead.
This parameter must be NULL for GUI or console processes that do not create a new
console window.
dwX
If dwFlags specifies STARTF_USEPOSITION, this member is the x offset of the upper left
corner of a window if a new window is created, in pixels. Otherwise, this member is
ignored.
The offset is from the upper left corner of the screen. For GUI processes, the specified
position is used the first time the new process calls CreateWindow to create an
overlapped window if the x parameter of CreateWindow is CW_USEDEFAULT.
dwY
If dwFlags specifies STARTF_USEPOSITION, this member is the y offset of the upper left
corner of a window if a new window is created, in pixels. Otherwise, this member is
ignored.
The offset is from the upper left corner of the screen. For GUI processes, the specified
position is used the first time the new process calls CreateWindow to create an
overlapped window if the y parameter of CreateWindow is CW_USEDEFAULT.
dwXSize
If dwFlags specifies STARTF_USESIZE, this member is the width of the window if a new
window is created, in pixels. Otherwise, this member is ignored.
For GUI processes, this is used only the first time the new process calls CreateWindow to
create an overlapped window if the nWidth parameter of CreateWindow is
CW_USEDEFAULT.
dwYSize
If dwFlags specifies STARTF_USESIZE, this member is the height of the window if a new
window is created, in pixels. Otherwise, this member is ignored.
For GUI processes, this is used only the first time the new process calls CreateWindow to
create an overlapped window if the nHeight parameter of CreateWindow is
CW_USEDEFAULT.
dwXCountChars
dwYCountChars
dwFillAttribute
dwFlags
A bitfield that determines whether certain STARTUPINFO members are used when the
process creates a window. This member can be one or more of the following values.
Value Meaning
The system turns the feedback cursor off after the first
call to GetMessage, regardless of whether the process is
drawing.
STARTF_FORCEOFFFEEDBACK Indicates that the feedback cursor is forced off while the
0x00000080 process is starting. The Normal Select cursor is displayed.
STARTF_TITLEISLINKNAME The lpTitle member contains the path of the shortcut file
0x00000800 (.lnk) that the user invoked to start this process. This is
typically set by the shell when a .lnk file pointing to the
launched application is invoked. Most applications will
not need to set this value.
wShowWindow
For GUI processes, the first time ShowWindow is called, its nCmdShow parameter is
ignored wShowWindow specifies the default value. In subsequent calls to ShowWindow,
the wShowWindow member is used if the nCmdShow parameter of ShowWindow is set
to SW_SHOWDEFAULT.
cbReserved2
hStdInput
hStdOutput
If a process is launched from the taskbar or jump list, the system sets hStdOutput to a
handle to the monitor that contains the taskbar or jump list used to launch the process.
For more information, see Remarks.Windows 7, Windows Server 2008 R2,
Windows Vista, Windows Server 2008, Windows XP and Windows Server 2003: This
behavior was introduced in Windows 8 and Windows Server 2012.
hStdError
Remarks
For graphical user interface (GUI) processes, this information affects the first window
created by the CreateWindow function and shown by the ShowWindow function. For
console processes, this information affects the console window if a new console is
created for the process. A process can use the GetStartupInfo function to retrieve the
STARTUPINFO structure specified when the process was created.
If a GUI process is being started and neither STARTF_FORCEONFEEDBACK or
STARTF_FORCEOFFFEEDBACK is specified, the process feedback cursor is used. A GUI
process is one whose subsystem is specified as "windows."
If a process is launched from the taskbar or jump list, the system sets GetStartupInfo to
retrieve the STARTUPINFO structure and check that hStdOutput is set. If so, use
GetMonitorInfo to check whether hStdOutput is a valid monitor handle (HMONITOR).
The process can then use the handle to position its windows.
Examples
C++
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
if( argc != 2 )
{
printf("Usage: %s [cmdline]\n", argv[0]);
return;
}
7 Note
Requirements
See also
CreateProcess
CreateProcessAsUser
CreateProcessWithLogonW
CreateProcessWithTokenW
GetStartupInfo
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
DWORD SuspendThread(
[in] HANDLE hThread
);
Parameters
[in] hThread
The handle must have the THREAD_SUSPEND_RESUME access right. For more
information, see Thread Security and Access Rights.
Return value
If the function succeeds, the return value is the thread's previous suspend count;
otherwise, it is (DWORD) -1 . To get extended error information, use the GetLastError
function.
Remarks
If the function succeeds, execution of the specified thread is suspended and the thread's
suspend count is incremented. Suspending a thread causes the thread to stop executing
user-mode (application) code.
This function is primarily designed for use by debuggers. It is not intended to be used
for thread synchronization. Calling SuspendThread on a thread that owns a
synchronization object, such as a mutex or critical section, can lead to a deadlock if the
calling thread tries to obtain a synchronization object owned by a suspended thread. To
avoid this situation, a thread within an application that is not a debugger should signal
the other thread to suspend itself. The target thread must be designed to watch for this
signal and respond appropriately.
Windows Phone 8.1: This function is supported for Windows Phone Store apps on
Windows Phone 8.1 and later.
Windows 8.1 and Windows Server 2012 R2: This function is supported for Windows
Store apps on Windows 8.1, Windows Server 2012 R2, and later.
Requirements
See also
OpenThread
ResumeThread
Threads
Feedback
Was this page helpful? ツ Yes ト No
Causes the calling thread to yield execution to another thread that is ready to run on the
current processor. The operating system selects the next thread to be executed.
Syntax
C++
BOOL SwitchToThread();
Return value
If calling the SwitchToThread function caused the operating system to switch execution
to another thread, the return value is nonzero.
If there are no other threads ready to execute, the operating system does not switch
execution to another thread, and the return value is zero.
Remarks
The yield of execution is in effect for up to one thread-scheduling time slice on the
processor of the calling thread. The operating system will not switch execution to
another processor, even if that processor is idle or is running a thread of lower priority.
After the yielding thread's time slice elapses, the operating system reschedules
execution for the yielding thread. The rescheduling is determined by the priority of the
yielding thread and the status of other threads that are available to run.
Note that the operating system will not switch to a thread that is being prevented from
running only by concurrency control. For example, an I/O completion port or thread
pool limits the number of associated threads that can run. If the maximum number of
threads is already running, no additional associated thread can run until a running
thread finishes. If a thread uses SwitchToThread to wait for one of the additional
associated threads to accomplish some work, the process might deadlock.
To compile an application that uses this function, define _WIN32_WINNT as 0x0400 or
later. For more information, see Using the Windows Headers.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
Process and Thread Functions
SuspendThread
Threads
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
BOOL TerminateProcess(
[in] HANDLE hProcess,
[in] UINT uExitCode
);
Parameters
[in] hProcess
The handle must have the PROCESS_TERMINATE access right. For more information, see
Process Security and Access Rights.
[in] uExitCode
The exit code to be used by the process and threads terminated as a result of this call.
Use the GetExitCodeProcess function to retrieve a process's exit value. Use the
GetExitCodeThread function to retrieve a thread's exit value.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
The TerminateProcess function is used to unconditionally cause a process to exit. The
state of global data maintained by dynamic-link libraries (DLLs) may be compromised if
TerminateProcess is used rather than ExitProcess.
This function stops execution of all threads within the process and requests cancellation
of all pending I/O. The terminated process cannot exit until all pending I/O has been
completed or canceled. When a process terminates, its kernel object is not destroyed
until all processes that have open handles to the process have released those handles.
After a process has terminated, call to TerminateProcess with open handles to the
process fails with ERROR_ACCESS_DENIED (5) error code.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
ExitProcess
GetExitCodeProcess
GetExitCodeThread
OpenProcess
Processes
Terminating a Process
Feedback
Was this page helpful? ツ Yes ト No
Terminates a thread.
Syntax
C++
BOOL TerminateThread(
[in, out] HANDLE hThread,
[in] DWORD dwExitCode
);
Parameters
[in, out] hThread
The handle must have the THREAD_TERMINATE access right. For more information, see
Thread Security and Access Rights.
[in] dwExitCode
The exit code for the thread. Use the GetExitCodeThread function to retrieve a thread's
exit value.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
TerminateThread is used to cause a thread to exit. When this occurs, the target thread
has no chance to execute any user-mode code. DLLs attached to the thread are not
notified that the thread is terminating. The system frees the thread's initial stack.
Windows Server 2003 and Windows XP: The target thread's initial stack is not freed,
causing a resource leak.
TerminateThread is a dangerous function that should only be used in the most extreme
cases. You should call TerminateThread only if you know exactly what the target thread
is doing, and you control all of the code that the target thread could possibly be
running at the time of the termination. For example, TerminateThread can result in the
following problems:
If the target thread owns a critical section, the critical section will not be released.
If the target thread is allocating memory from the heap, the heap lock will not be
released.
If the target thread is executing certain kernel32 calls when it is terminated, the
kernel32 state for the thread's process could be inconsistent.
If the target thread is manipulating the global state of a shared DLL, the state of
the DLL could be destroyed, affecting other users of the DLL.
A thread cannot protect itself against TerminateThread, other than by controlling access
to its handles. The thread handle returned by the CreateThread and CreateProcess
functions has THREAD_TERMINATE access, so any caller holding one of these handles
can terminate your thread.
If the target thread is the last thread of a process when this function is called, the
thread's process is also terminated.
The state of the thread object becomes signaled, releasing any other threads that had
been waiting for the thread to terminate. The thread's termination status changes from
STILL_ACTIVE to the value of the dwExitCode parameter.
Terminating a thread does not necessarily remove the thread object from the system. A
thread object is deleted when the last thread handle is closed.
Requirements
Target Windows
Platform
Library Kernel32.lib
DLL Kernel32.dll
See also
CreateProcess
CreateThread
ExitThread
GetExitCodeThread
OpenThread
Terminating a Thread
Threads
Feedback
Was this page helpful? ツ Yes ト No
Syntax
C++
Constants
ThreadMemoryPriority
Lower the memory priority of threads that perform background operations or access files and
data that are not expected to be accessed frequently.
ThreadAbsoluteCpuPriority
CPU priority.
ThreadDynamicCodePolicy
Generate dynamic code or modify executable code.
ThreadPowerThrottling
Throttle the target process activity for power management.
ThreadInformationClassMax
Requirements
See also
UnmapViewOfFile2 function, UnmapViewOfFileEx function, GetThreadInformation
function, SetThreadInformation function,
PROCESS_MITIGATION_DYNAMIC_CODE_POLICY structure,
Feedback
Was this page helpful? ツ Yes ト No
Specifies the throttling policies and how to apply them to a target thread when that
thread is subject to power management. This structure is used by the
SetThreadInformation function.
Syntax
C++
Members
Version
Value Meaning
ControlMask
This field enables the caller to take control of the power throttling mechanism.
Value Meaning
StateMask
Value Meaning
Value Meaning
Requirements
Header processthreadsapi.h
Feedback
Was this page helpful? ツ Yes ト No
Allocates a thread local storage (TLS) index. Any thread of the process can subsequently
use this index to store and retrieve values that are local to the thread, because each
thread receives its own slot for the index.
Syntax
C++
DWORD TlsAlloc();
Return value
If the function succeeds, the return value is a TLS index. The slots for the index are
initialized to zero.
If the function fails, the return value is TLS_OUT_OF_INDEXES. To get extended error
information, call GetLastError.
Remarks
Windows Phone 8.1: This function is supported for Windows Phone Store apps on
Windows Phone 8.1 and later. When a Windows Phone Store app calls this function, it is
replaced with an inline call to FlsAlloc. Refer to FlsAlloc for function documentation.
Windows 8.1, Windows Server 2012 R2, and Windows 10, version 1507: This function is
supported for Windows Store apps on Windows 8.1, Windows Server 2012 R2, and
Windows 10, version 1507. When a Windows Store app calls this function, it is replaced
with an inline call to FlsAlloc. Refer to FlsAlloc for function documentation.
Windows 10, version 1511 and Windows 10, version 1607: This function is fully
supported for Universal Windows Platform (UWP) apps, and is no longer replaced with
an inline call to FlsAlloc.
The threads of the process can use the TLS index in subsequent calls to the TlsFree,
TlsSetValue, or TlsGetValue functions. The value of the TLS index should be treated as an
opaque value; do not assume that it is an index into a zero-based array.
TLS indexes are typically allocated during process or dynamic-link library (DLL)
initialization. When a TLS index is allocated, its storage slots are initialized to NULL. After
a TLS index has been allocated, each thread of the process can use it to access its own
TLS storage slot. To store a value in its TLS slot, a thread specifies the index in a call to
TlsSetValue. The thread specifies the same index in a subsequent call to TlsGetValue, to
retrieve the stored value.
TLS indexes are not valid across process boundaries. A DLL cannot assume that an index
assigned in one process is valid in another process.
Examples
For an example, see Using Thread Local Storage or Using Thread Local Storage in a
Dynamic-Link Library.
Requirements
See also
Process and Thread Functions
TlsFree
TlsGetValue
TlsSetValue
Feedback
Was this page helpful? ツ Yes ト No
Releases a thread local storage (TLS) index, making it available for reuse.
Syntax
C++
BOOL TlsFree(
[in] DWORD dwTlsIndex
);
Parameters
[in] dwTlsIndex
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
Windows Phone 8.1: This function is supported for Windows Phone Store apps on
Windows Phone 8.1 and later. When a Windows Phone Store app calls this function, it is
replaced with an inline call to FlsFree. Refer to FlsFree for function documentation.
Windows 8.1, Windows Server 2012 R2, and Windows 10, version 1507: This function is
supported for Windows Store apps on Windows 8.1, Windows Server 2012 R2, and
Windows 10, version 1507. When a Windows Store app calls this function, it is replaced
with an inline call to FlsFree. Refer to FlsFree for function documentation.
Windows 10, version 1511 and Windows 10, version 1607: This function is fully
supported for Universal Windows Platform (UWP) apps, and is no longer replaced with
an inline call to FlsFree.
If the threads of the process have allocated memory and stored a pointer to the
memory in a TLS slot, they should free the memory before calling TlsFree. The TlsFree
function does not free memory blocks whose addresses have been stored in the TLS
slots associated with the TLS index. It is expected that DLLs call this function (if at all)
only during DLL_PROCESS_DETACH.
Examples
For an example, see Using Thread Local Storage or Using Thread Local Storage in a
Dynamic-Link Library.
Requirements
See also
Processes and Threads Overview
TlsAlloc
TlsGetValue
TlsSetValue
Feedback
Was this page helpful? ツ Yes ト No
Retrieves the value in the calling thread's thread local storage (TLS) slot for the specified
TLS index. Each thread of a process has its own slot for each TLS index.
Syntax
C++
LPVOID TlsGetValue(
[in] DWORD dwTlsIndex
);
Parameters
[in] dwTlsIndex
Return value
If the function succeeds, the return value is the value stored in the calling thread's TLS
slot associated with the specified index. If dwTlsIndex is a valid index allocated by a
successful call to TlsAlloc, this function always succeeds.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
The data stored in a TLS slot can have a value of 0 because it still has its initial value or
because the thread called the TlsSetValue function with 0. Therefore, if the return value
is 0, you must check whether GetLastError returns ERROR_SUCCESS before determining
that the function has failed. If GetLastError returns ERROR_SUCCESS, then the function
has succeeded and the data stored in the TLS slot is 0. Otherwise, the function has
failed.
Functions that return indications of failure call SetLastError when they fail. They
generally do not call SetLastError when they succeed. The TlsGetValue function is an
exception to this general rule. The TlsGetValue function calls SetLastError to clear a
thread's last error when it succeeds. That allows checking for the error-free retrieval of
zero values.
Remarks
Windows Phone 8.1: This function is supported for Windows Phone Store apps on
Windows Phone 8.1 and later. When a Windows Phone Store app calls this function, it is
replaced with an inline call to FlsGetValue. Refer to FlsGetValue for function
documentation.
Windows 8.1, Windows Server 2012 R2, and Windows 10, version 1507: This function is
supported for Windows Store apps on Windows 8.1, Windows Server 2012 R2, and
Windows 10, version 1507. When a Windows Store app calls this function, it is replaced
with an inline call to FlsGetValue. Refer to FlsGetValue for function documentation.
Windows 10, version 1511 and Windows 10, version 1607: This function is fully
supported for Universal Windows Platform (UWP) apps, and is no longer replaced with
an inline call to FlsGetValue.
TLS indexes are typically allocated by the TlsAlloc function during process or DLL
initialization. After a TLS index is allocated, each thread of the process can use it to
access its own TLS slot for that index. A thread specifies a TLS index in a call to
TlsSetValue to store a value in its slot. The thread specifies the same index in a
subsequent call to TlsGetValue to retrieve the stored value.
TlsGetValue was implemented with speed as the primary goal. The function performs
minimal parameter validation and error checking. In particular, it succeeds if dwTlsIndex
is in the range 0 through (TLS_MINIMUM_AVAILABLE– 1). It is up to the programmer to
ensure that the index is valid and that the thread calls TlsSetValue before calling
TlsGetValue.
Examples
For an example, see Using Thread Local Storage or Using Thread Local Storage in a
Dynamic-Link Library.
Requirements
Minimum Windows XP [desktop apps | UWP apps]
supported client
See also
Process and Thread Functions
TlsAlloc
TlsFree
TlsSetValue
Feedback
Was this page helpful? ツ Yes ト No
Stores a value in the calling thread's thread local storage (TLS) slot for the specified TLS
index. Each thread of a process has its own slot for each TLS index.
Syntax
C++
BOOL TlsSetValue(
[in] DWORD dwTlsIndex,
[in, optional] LPVOID lpTlsValue
);
Parameters
[in] dwTlsIndex
The value to be stored in the calling thread's TLS slot for the index.
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call
GetLastError.
Remarks
Windows Phone 8.1: This function is supported for Windows Phone Store apps on
Windows Phone 8.1 and later. When a Windows Phone Store app calls this function, it is
replaced with an inline call to FlsSetValue. Refer to FlsSetValue for function
documentation.
Windows 8.1, Windows Server 2012 R2, and Windows 10, version 1507: This function is
supported for Windows Store apps on Windows 8.1, Windows Server 2012 R2, and
Windows 10, version 1507. When a Windows Store app calls this function, it is replaced
with an inline call to FlsSetValue. Refer to FlsSetValue for function documentation.
Windows 10, version 1511 and Windows 10, version 1607: This function is fully
supported for Universal Windows Platform (UWP) apps, and is no longer replaced with
an inline call to FlsSetValue.
TLS indexes are typically allocated by the TlsAlloc function during process or DLL
initialization. When a TLS index is allocated, its storage slots are initialized to NULL. After
a TLS index is allocated, each thread of the process can use it to access its own TLS slot
for that index. A thread specifies a TLS index in a call to TlsSetValue, to store a value in
its slot. The thread specifies the same index in a subsequent call to TlsGetValue, to
retrieve the stored value.
TlsSetValue was implemented with speed as the primary goal. The function performs
minimal parameter validation and error checking. In particular, it succeeds if dwTlsIndex
is in the range 0 through (TLS_MINIMUM_AVAILABLE – 1). It is up to the programmer to
ensure that the index is valid before calling TlsGetValue.
Examples
For an example, see Using Thread Local Storage or Using Thread Local Storage in a
Dynamic-Link Library.
Requirements
TlsAlloc
TlsFree
TlsGetValue
Feedback
Was this page helpful? ツ Yes ト No
Updates the specified attribute in a list of attributes for process and thread creation.
Syntax
C++
BOOL UpdateProcThreadAttribute(
[in, out] LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList,
[in] DWORD dwFlags,
[in] DWORD_PTR Attribute,
[in] PVOID lpValue,
[in] SIZE_T cbSize,
[out, optional] PVOID lpPreviousValue,
[in, optional] PSIZE_T lpReturnSize
);
Parameters
[in, out] lpAttributeList
[in] dwFlags
[in] Attribute
The attribute key to update in the attribute list. This parameter can be one of the following values.
Value Meaning
[in] lpValue
A pointer to the attribute value. This value must persist until the attribute list is destroyed using
the DeleteProcThreadAttributeList function.
[in] cbSize
Return value
If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
An attribute list is an opaque structure that consists of a series of key/value pairs, one for each
attribute. A process can update only the attribute keys described in this topic.
The DWORD or DWORD64 pointed to by lpValue can be one or more of the following values when
you specify PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY for the Attribute parameter:
The following mitigation options are available for mandatory ASLR policy:
PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON (0x00000001
<< 8)
PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_OFF
(0x00000002 << 8)
PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON_REQ_RELOCS
(0x00000003 << 8)
The heap terminate on corruption policy, if enabled, causes the heap to terminate if it becomes
corrupt. Note that 'always off' does not override the default opt-in for binaries with current
subsystem versions set in the image header. Heap terminate on corruption is user mode enforced.
The following mitigation options are available for heap terminate on corruption policy:
PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_ALWAYS_ON (0x00000001 << 12)
PROCESS_CREATION_MITIGATION_POLICY_HEAP_TERMINATE_ALWAYS_OFF (0x00000002 << 12)
The bottom-up randomization policy, which includes stack randomization options, causes a
random location to be used as the lowest user address.
The following mitigation options are available for the bottom-up randomization policy:
PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_ON (0x00000001 << 16)
PROCESS_CREATION_MITIGATION_POLICY_BOTTOM_UP_ASLR_ALWAYS_OFF (0x00000002 << 16)
The high-entropy bottom-up randomization policy, if enabled, causes up to 1TB of bottom-up
variance to be used. Note that high-entropy bottom-up randomization is effective if and only if
bottom-up ASLR is also enabled; high-entropy bottom-up randomization is only meaningful for
native 64-bit processes.
The following mitigation options are available for the high-entropy bottom-up randomization
policy:
PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_ALWAYS_ON (0x00000001 <<
20)
PROCESS_CREATION_MITIGATION_POLICY_HIGH_ENTROPY_ASLR_ALWAYS_OFF (0x00000002 <<
20)
The strict handle checking enforcement policy, if enabled, causes an exception to be raised
immediately on a bad handle reference. If this policy is not enabled, a failure status will be returned
from the handle reference instead.
The following mitigation options are available for the strict handle checking enforcement policy:
PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_ALWAYS_ON (0x00000001
<< 24)
PROCESS_CREATION_MITIGATION_POLICY_STRICT_HANDLE_CHECKS_ALWAYS_OFF (0x00000002
<< 24)
The Win32k system call disable policy, if enabled, prevents a process from making Win32k calls.
The following mitigation options are available for the Win32k system call disable policy:
PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_ON
(0x00000001 << 28)
PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_OFF
(0x00000002 << 28)
The Extension Point Disable policy, if enabled, prevents certain built-in third party extension points
from being used. This policy blocks the following extension points:
AppInit DLLs
Winsock Layered Service Providers (LSPs)
Global Windows Hooks
Legacy Input Method Editors (IMEs)
Local hooks still work with the Extension Point Disable policy enabled. This behavior is used to
prevent legacy extension points from being loaded into a process that does not use them.
The following mitigation options are available for the extension point disable policy:
PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_ON
(0x00000001 << 32)
PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_OFF
(0x00000002 << 32)
The Control Flow Guard (CFG) policy, if turned on, places additional restrictions on indirect calls in
code that has been built with CFG enabled.
The following mitigation options are available for controlling the CFG policy:
PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_MASK
(0x00000003ui64 << 40)
PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_DEFER
(0x00000000ui64 << 40)
PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_ON
(0x00000001ui64 << 40)
PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_OFF
(0x00000002ui64 << 40)
PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_EXPORT_SUPPRESSION
(0x00000003ui64 << 40)
In addition, the following policy can be specified to enforce that EXEs/DLLs must enable CFG. If an
attempt is made to load an EXE/DLL that does not enable CFG, the load will fail:
PROCESS_CREATION_MITIGATION_POLICY2_STRICT_CONTROL_FLOW_GUARD_MASK
(0x00000003ui64 << 8)
PROCESS_CREATION_MITIGATION_POLICY2_STRICT_CONTROL_FLOW_GUARD_DEFER
(0x00000000ui64 << 8)
PROCESS_CREATION_MITIGATION_POLICY2_STRICT_CONTROL_FLOW_GUARD_ALWAYS_ON
(0x00000001ui64 << 8)
PROCESS_CREATION_MITIGATION_POLICY2_STRICT_CONTROL_FLOW_GUARD_ALWAYS_OFF
(0x00000002ui64 << 8)
PROCESS_CREATION_MITIGATION_POLICY2_STRICT_CONTROL_FLOW_GUARD_RESERVED
(0x00000003ui64 << 8)
The dynamic code policy, if turned on, prevents a process from generating dynamic code or
modifying executable code.
The following mitigation options are available for the dynamic code policy:
PROCESS_CREATION_MITIGATION_POLICY_PROHIBIT_DYNAMIC_CODE_MASK (0x00000003ui64
<< 36)
PROCESS_CREATION_MITIGATION_POLICY_PROHIBIT_DYNAMIC_CODE_DEFER (0x00000000ui64
<< 36)
PROCESS_CREATION_MITIGATION_POLICY_PROHIBIT_DYNAMIC_CODE_ALWAYS_ON
(0x00000001ui64 << 36)
PROCESS_CREATION_MITIGATION_POLICY_PROHIBIT_DYNAMIC_CODE_ALWAYS_OFF
(0x00000002ui64 << 36)
PROCESS_CREATION_MITIGATION_POLICY_PROHIBIT_DYNAMIC_CODE_ALWAYS_ON_ALLOW_OPT_OUT
(0x00000003ui64 << 36)
The binary signature policy requires EXEs/DLLs to be properly signed.
The following mitigation options are available for the binary signature policy:
PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_MASK
(0x00000003ui64 << 44)
PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_DEFER
(0x00000000ui64 << 44)
PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_ON
(0x00000001ui64 << 44)
PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALWAYS_OFF
(0x00000002ui64 << 44)
PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARIES_ALLOW_STORE
(0x00000003ui64 << 44)
The font loading prevention policy for the process determines whether non-system fonts can be
loaded for a process. When the policy is turned on, the process is prevented from loading non-
system fonts.
The following mitigation options are available for the font loading prevention policy:
PROCESS_CREATION_MITIGATION_POLICY_FONT_DISABLE_MASK (0x00000003ui64 << 48)
PROCESS_CREATION_MITIGATION_POLICY_FONT_DISABLE_DEFER (0x00000000ui64 << 48)
PROCESS_CREATION_MITIGATION_POLICY_FONT_DISABLE_ALWAYS_ON (0x00000001ui64 << 48)
PROCESS_CREATION_MITIGATION_POLICY_FONT_DISABLE_ALWAYS_OFF (0x00000002ui64 << 48)
PROCESS_CREATION_MITIGATION_POLICY_AUDIT_NONSYSTEM_FONTS (0x00000003ui64 << 48)
The image loading policy of the process determines the types of executable images that can be
mapped into the process. When the policy is turned on, images cannot be loaded from some
locations, such as remove devices or files that have the Low mandatory label.
The following mitigation options are available for the image loading policy:
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_REMOTE_MASK (0x00000003ui64
<< 52)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_REMOTE_DEFER (0x00000000ui64
<< 52)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_REMOTE_ALWAYS_ON
(0x00000001ui64 << 52)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_REMOTE_ALWAYS_OFF
(0x00000002ui64 << 52)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_REMOTE_RESERVED
(0x00000003ui64 << 52)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_LOW_LABEL_MASK
(0x00000003ui64 << 56)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_LOW_LABEL_DEFER
(0x00000000ui64 << 56)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_LOW_LABEL_ALWAYS_ON
(0x00000001ui64 << 56)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_LOW_LABEL_ALWAYS_OFF
(0x00000002ui64 << 56)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_LOW_LABEL_RESERVED
(0x00000003ui64 << 56)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_MASK
(0x00000003ui64 << 60)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_DEFER
(0x00000000ui64 << 60)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_ALWAYS_ON
(0x00000001ui64 << 60)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_ALWAYS_OFF
(0x00000002ui64 << 60)
PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_RESERVED
(0x00000003ui64 << 60)
Windows 10, version 1709: The following value is available only in Windows 10, version 1709 or
later and only with the January 2018 Windows security updates and any applicable firmware
updates from the OEM device manufacturer. See Windows Client Guidance for IT Pros to protect
against speculative execution side-channel vulnerabilities .
PROCESS_CREATION_MITIGATION_POLICY2_RESTRICT_INDIRECT_BRANCH_PREDICTION_ALWAYS_ON
(0x00000001ui64 << 16)This flag can be used by processes to protect against sibling hardware
threads (hyperthreads) from interfering with indirect branch predictions. Processes that have
sensitive information in their address space should consider enabling this flag to protect against
attacks involving indirect branch prediction (such as CVE-2017-5715).
Windows 10, version 1809: The following value is available only in Windows 10, version 1809 or
later.
PROCESS_CREATION_MITIGATION_POLICY2_SPECULATIVE_STORE_BYPASS_DISABLE_ALWAYS_ON
(0x00000001ui64 << 24)This flag can be used by processes to disable the Speculative Store Bypass
(SSB) feature of CPUs that may be vulnerable to speculative execution side channel attacks
involving SSB (CVE-2018-3639). This flag is only supported by certain Intel CPUs that have the
requisite hardware features. On CPUs that do not support this feature, the flag has no effect.
Windows 10, version 2004: The following values are available only in Windows 10, version 2004 or
later.
Hardware-enforced Stack Protection (HSP) is a hardware-based security feature where the CPU
verifies function return addresses at runtime by employing a shadow stack mechanism. For user-
mode HSP, the default mode is compatibility mode, where only shadow stack violations occurring
in modules that are considered compatible with shadow stacks (CETCOMPAT) are fatal. In strict
mode, all shadow stack violations are fatal.
The following mitigation options are available for user-mode Hardware-enforced Stack Protection
and related features:
PROCESS_CREATION_MITIGATION_POLICY2_CET_USER_SHADOW_STACKS_ALWAYS_ON
(0x00000001ui64 << 28)
PROCESS_CREATION_MITIGATION_POLICY2_CET_USER_SHADOW_STACKS_ALWAYS_OFF
(0x00000002ui64 << 28)
PROCESS_CREATION_MITIGATION_POLICY2_CET_USER_SHADOW_STACKS_STRICT_MODE
(0x00000003ui64 << 28)
Restricting certain HSP APIs used to specify security properties of dynamic code to only be callable
from outside of the process:
PROCESS_CREATION_MITIGATION_POLICY2_CET_DYNAMIC_APIS_OUT_OF_PROC_ONLY_ALWAYS_ON
(0x00000001ui64 << 48)
PROCESS_CREATION_MITIGATION_POLICY2_CET_DYNAMIC_APIS_OUT_OF_PROC_ONLY_ALWAYS_OFF
(0x00000002ui64 << 48)
The FSCTL system call disable policy, if enabled, prevents a process from making NtFsControlFile
calls. The following mitigation options are available for the FSCTL system call disable policy:
PROCESS_CREATION_MITIGATION_POLICY2_FSCTL_SYSTEM_CALL_DISABLE_ALWAYS_ON
(0x00000001ui64 << 56)
PROCESS_CREATION_MITIGATION_POLICY2_FSCTL_SYSTEM_CALL_DISABLE_ALWAYS_OFF
(0x00000002ui64 << 56)
The DWORD pointed to by lpValue can be one or more of the following values when you specify
PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY for the Attribute parameter:
PROCESS_CREATION_CHILD_PROCESS_RESTRICTED 0x01
The process being created is not allowed to create child processes. This restriction becomes a
property of the token as which the process runs. It should be noted that this restriction is only
effective in sandboxed applications (such as AppContainer) which ensure privileged process
handles are not accessible to the process. For example, if a process restricting child process
creation is able to access another process handle with PROCESS_CREATE_PROCESS or
PROCESS_VM_WRITE access rights, then it may be possible to bypass the child process restriction.
PROCESS_CREATION_CHILD_PROCESS_OVERRIDE 0x02
The process being created is allowed to create a child process, if it would otherwise be restricted.
You can only specify this value if the process that is creating the new process is not restricted.
The DWORD pointed to by lpValue can be one or more of the following values when you specify
PROC_THREAD_ATTRIBUTE_DESKTOP_APP_POLICY for the Attribute parameter:
PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_ENABLE_PROCESS_TREE 0x01
The process being created will create any child processes outside of the desktop app runtime
environment. This behavior is the default for processes for which no policy has been set.
PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_DISABLE_PROCESS_TREE 0x02
The process being created will create any child processes inside of the desktop app runtime
environment. This policy is inherited by the descendant processes until it is overridden by creating
a process with PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_ENABLE_PROCESS_TREE.
PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_OVERRIDE 0x04
The process being created will run inside the desktop app runtime environment. This policy applies
only to the process being created, not its descendants..
In order to launch the child process with the same protection level as the parent, the parent
process must specify the PROC_THREAD_ATTRIBUTE_PROTECTION_LEVEL attribute for the child
process. This can be used for both protected and unprotected processes. For example, when this
flag is used by an unprotected process, the system will launch a child process at unprotected level.
The CREATE_PROTECTED_PROCESS flag must be specified in both cases.
The following example launches a child process with the same protection level as the parent
process:
C++
DWORD ProtectionLevel = PROTECTION_LEVEL_SAME;
SIZE_T AttributeListSize;
STARTUPINFOEXW StartupInfoEx = { 0 };
StartupInfoEx.StartupInfo.cb = sizeof(StartupInfoEx);
InitializeProcThreadAttributeList(NULL, 1, 0, &AttributeListSize)
if (InitializeProcThreadAttributeList(StartupInfoEx.lpAttributeList,
1,
0,
&AttributeListSize) == FALSE)
{
Result = GetLastError();
goto exitFunc;
}
if (UpdateProcThreadAttribute(StartupInfoEx.lpAttributeList,
0,
PROC_THREAD_ATTRIBUTE_PROTECTION_LEVEL,
&ProtectionLevel,
sizeof(ProtectionLevel),
NULL,
NULL) == FALSE)
{
Result = GetLastError();
goto exitFunc;
}
PROCESS_INFORMATION ProcessInformation = { 0 };
if (CreateProcessW(ApplicationName,
CommandLine,
ProcessAttributes,
ThreadAttributes,
InheritHandles,
EXTENDED_STARTUPINFO_PRESENT | CREATE_PROTECTED_PROCESS,
Environment,
CurrentDirectory,
(LPSTARTUPINFOW)&StartupInfoEx,
&ProcessInformation) == FALSE)
{
Result = GetLastError();
goto exitFunc;
}
Requirements
Minimum supported Windows Vista [desktop apps only]
client
Library Kernel32.lib
DLL Kernel32.dll
See also
DeleteProcThreadAttributeList
InitializeProcThreadAttributeList
Feedback
Was this page helpful? Yes No