SlideShare a Scribd company logo
1 of 30
Download to read offline
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
常用的 API 函数
1.ProcessIdToSessionId Function
Retrieves the Remote Desktop Services session associated with a
specified process.
Syntax
C++
BOOL ProcessIdToSessionId(
__in DWORD dwProcessId,
__out DWORD *pSessionId
);
Parameters
dwProcessId [in]
Specifies a process identifier. Use the GetCurrentProcessId
function to retrieve the process identifier for the current
process.
pSessionId [out]
Pointer to a variable that receives the identifier of the Remote
Desktop Services session under which the specified process is
running. To retrieve the identifier of the session currently
attached to the console, use the
WTSGetActiveConsoleSessionId function.
Return Value
If the function succeeds, the return value is a nonzero value.
If the function fails, the return value is zero. To get extended error
information, call GetLastError.
Remarks
Callers must hold the PROCESS_QUERY_INFORMATION access right
for the specified process. For more information, see Process Security
and Access Rights.
Requirements
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
Minimum supported client Windows 2000 Professional
Minimum supported server Windows 2000 Server
Header Winbase.h (include Windows.h)
Library Kernel32.lib
DLL Kernel32.dll
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
2.GetCurrentDirectory Function
Retrieves the current directory for the current process.
Syntax
C++
DWORD WINAPI GetCurrentDirectory(
__in DWORD nBufferLength,
__out LPTSTR lpBuffer
);
Parameters
nBufferLength [in]
The length of the buffer for the current directory string, in
TCHARs. The buffer length must include room for a terminating
null character.
lpBuffer [out]
A pointer to the buffer that receives the current directory string.
This null-terminated string specifies the absolute path to the
current directory.
To determine the required buffer size, set this parameter to
NULL and the nBufferLength parameter to 0.
Return Value
If the function succeeds, the return value specifies the number of
characters that are written to the buffer, not including the terminating
null character.
If the function fails, the return value is zero. To get extended error
information, call GetLastError.
If the buffer that is pointed to by lpBuffer is not large enough, the
return value specifies the required size of the buffer, in characters,
including the null-terminating character.
Remarks
Each process has a single current directory that consists of two parts:
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
• A disk designator that is either a drive letter followed by a colon,
or a server name followed by a share name
(servernamesharename)
• A directory on the disk designator
To set the current directory, use the SetCurrentDirectory function.
Multithreaded applications and shared library code should not use the
GetCurrentDirectory function and should avoid using relative path
names. The current directory state written by the
SetCurrentDirectory function is stored as a global variable in each
process, therefore multithreaded applications cannot reliably use this
value without possible data corruption from other threads that may
also be reading or setting this value. This limitation also applies to the
SetCurrentDirectory and GetFullPathName functions. The
exception being when the application is guaranteed to be running in a
single thread, for example parsing file names from the command line
argument string in the main thread prior to creating any additional
threads. Using relative path names in multithreaded applications or
shared library code can yield unpredictable results and is not
supported.
Examples
For an example, see Changing the Current Directory.
Requirements
Minimum
supported client
Windows 2000 Professional
Minimum
supported server
Windows 2000 Server
Header WinBase.h (include Windows.h)
Library Kernel32.lib
DLL Kernel32.dll
Unicode and
ANSI names
GetCurrentDirectoryW (Unicode) and
GetCurrentDirectoryA (ANSI)
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
3. SetCurrentDirectory
C++
BOOL WINAPI SetCurrentDirectory(
__in LPCTSTR lpPathName
);
Parameters
lpPathName [in]
The path to the new current directory. This parameter may
specify a relative path or a full path. In either case, the full path
of the specified directory is calculated and stored as the current
directory. For more information, see File Names, Paths, and
Namespaces.
The string must not exceed MAX_PATH characters, including
the terminating null character. The final character before the
null character must be a backslash (''). If you do not specify the
backslash, it will be added for you; therefore, specify
MAX_PATH-2 characters for the path unless you include the
trailing backslash, in which case, specify MAX_PATH-1
characters for the path.
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
Each process has a single current directory made up of two parts:
• A disk designator that is either a drive letter followed by a colon,
or a server name and share name (servernamesharename)
• A directory on the disk designator
Multithreaded applications and shared library code should not use the
SetCurrentDirectory function and should avoid using relative path
names. The current directory state written by the
SetCurrentDirectory function is stored as a global variable in each
process, therefore multithreaded applications cannot reliably use this
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
value without possible data corruption from other threads that may
also be reading or setting this value. This limitation also applies to the
GetCurrentDirectory and GetFullPathName functions. The
exception being when the application is guaranteed to be running in a
single thread, for example parsing file names from the command line
argument string in the main thread prior to creating any additional
threads. Using relative path names in multithreaded applications or
shared library code can yield unpredictable results and is not
supported.
Examples
For an example, see Changing the Current Directory.
Requirements
Minimum
supported client
Windows 2000 Professional
Minimum
supported server
Windows 2000 Server
Header WinBase.h (include Windows.h)
Library Kernel32.lib
DLL Kernel32.dll
Unicode and
ANSI names
SetCurrentDirectoryW (Unicode) and
SetCurrentDirectoryA (ANSI)
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
4. Gets
char *gets(
char *buffer
);
wchar_t *_getws(
wchar_t *buffer
);
Parameter
buffer
Storage location for input string.
Return Value
Returns its argument if successful. A NULL pointer indicates an error
or end-of-file condition. Use ferror or feof to determine which one has
occurred.
Remarks
The gets function reads a line from the standard input stream stdin
and stores it in buffer. The line consists of all characters up to and
including the first newline character ('n'). gets then replaces the
newline character with a null character ('0') before returning the line.
In contrast, the fgets function retains the newline character. _getws
is a wide-character version of gets; its argument and return value are
wide-character strings.
Security Note Because there is no way to limit the number of
characters read by gets, untrusted input can easily cause buffer
overruns. Use fgets instead.
Generic-Text Routine Mappings
TCHAR.H
routine
_UNICODE &
_MBCS not
defined
_MBCS
defined
_UNICODE
defined
_getts gets gets _getws
北京四元教育 http://www.bj111.cn
Requirements
Routine
Required
header Compatibility
gets <stdio.h> ANSI, Win 98, Win Me, Win NT, Win
2000, Win XP
_getws <stdio.h> or
<wchar.h>
ANSI, Win 98, Win Me, Win NT, Win
2000, Win XP
For additional compatibility information, see Compatibility in the
Introduction.
5 .MEMSET
void *memset(
void *dest,
int c,
size_t count
);
wchar_t *wmemset(
wchar_t *dest,
wchar_t c,
size_t count
);
Parameters
dest
Pointer to destination.
c
Character to set.
count
Number of characters.
Return Value
The value of dest.
Remarks
Sets the first count characters of dest to the character c.
Security Note Make sure that the destination buffer has enough
room for at least count characters. For more information, see
Avoiding Buffer Overruns.
Requirements
010-8956040,13691026331
北京四元教育 http://www.bj111.cn
Routine Required header
memset <memory.h> or <string.h>
wmemset <wchar.h>
For additional compatibility information, see Compatibility in the
Introduction.
Libraries
All versions of the C run-time libraries.
Example
Copy Code
// crt_memset.c
/* This program uses memset to
* set the first four chars of buffer to "*".
*/
#include <memory.h>
#include <stdio.h>
int main( void )
{
char buffer[] = "This is a test of the memset function";
printf( "Before: %sn", buffer );
memset( buffer, '*', 4 );
printf( "After: %sn", buffer );
}
Output
Before: This is a test of the memset function
After: **** is a test of the memset function
010-8956040,13691026331
北京四元教育 http://www.bj111.cn
6. fread
Reads data from a stream.
size_t fread(
void *buffer,
size_t size,
size_t count,
FILE *stream
);
Parameters
buffer
Storage location for data.
size
Item size in bytes.
count
Maximum number of items to be read.
stream
Pointer to FILE structure.
Return Value
fread returns the number of full items actually read, which may be
less than count if an error occurs or if the end of the file is encountered
before reaching count. Use the feof or ferror function to distinguish a
read error from an end-of-file condition. If size or count is 0, fread
returns 0 and the buffer contents are unchanged. If stream or buffer
is a null pointer, fread invokes the invalid parameter handler, as
described in Parameter Validation. If execution is allowed to continue,
this function sets errno to EINVAL and returns 0.
See _doserrno, errno, _sys_errlist, and _sys_nerr for more
information on these, and other, error codes.
Remarks
The fread function reads up to count items of size bytes from the
input stream and stores them in buffer. The file pointer associated
with stream (if there is one) is increased by the number of bytes
actually read. If the given stream is opened in text mode, carriage
return–linefeed pairs are replaced with single linefeed characters. The
replacement has no effect on the file pointer or the return value. The
file-pointer position is indeterminate if an error occurs. The value of a
partially read item cannot be determined.
010-8956040,13691026331
北京四元教育 http://www.bj111.cn
This function locks out other threads. If you need a non-locking
version, use _fread_nolock.
Requirements
Function Required header
fread <stdio.h>
For additional compatibility information, see Compatibility in the
Introduction.
Example
Copy Code
// crt_fread.c
// This program opens a file named FREAD.OUT and
// writes 25 characters to the file. It then tries to open
// FREAD.OUT and read in 25 characters. If the attempt succeeds,
// the program displays the number of actual items read.
#include <stdio.h>
int main( void )
{
FILE *stream;
char list[30];
int i, numread, numwritten;
// Open file in text mode:
if( fopen_s( &stream, "fread.out", "w+t" ) == 0 )
{
for ( i = 0; i < 25; i++ )
list[i] = (char)('z' - i);
// Write 25 characters to stream
numwritten = fwrite( list, sizeof( char ), 25, stream );
printf( "Wrote %d itemsn", numwritten );
fclose( stream );
}
else
printf( "Problem opening the filen" );
if( fopen_s( &stream, "fread.out", "r+t" ) == 0 )
{
// Attempt to read in 25 characters
numread = fread( list, sizeof( char ), 25, stream );
010-8956040,13691026331
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
printf( "Number of items read = %dn", numread );
printf( "Contents of buffer = %.25sn", list );
fclose( stream );
}
else
printf( "File could not be openedn" );
}
Copy Code
Wrote 25 items
Number of items read = 25
Contents of buffer = zyxwvutsrqponmlkjihgfedcb
7. CreateEvent Function
Creates or opens a named or unnamed event object.
To specify an access mask for the object, use the CreateEventEx
function.
Syntax
C++
HANDLE WINAPI CreateEvent(
__in_opt LPSECURITY_ATTRIBUTES lpEventAttributes,
__in BOOL bManualReset,
__in BOOL bInitialState,
__in_opt LPCTSTR lpName
);
Parameters
lpEventAttributes [in, optional]
A pointer to a SECURITY_ATTRIBUTES structure. If this
parameter is NULL, the handle cannot be inherited by child
processes.
The lpSecurityDescriptor member of the structure specifies a
security descriptor for the new event. If lpEventAttributes is
NULL, the event gets a default security descriptor. The ACLs in
the default security descriptor for an event come from the
primary or impersonation token of the creator.
bManualReset [in]
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
If this parameter is TRUE, the function creates a manual-reset
event object, which requires the use of the ResetEvent
function to set the event state to nonsignaled. If this parameter
is FALSE, the function creates an auto-reset event object, and
system automatically resets the event state to nonsignaled
after a single waiting thread has been released.
bInitialState [in]
If this parameter is TRUE, the initial state of the event object is
signaled; otherwise, it is nonsignaled.
lpName [in, optional]
The name of the event object. The name is limited to MAX_PATH
characters. Name comparison is case sensitive.
If lpName matches the name of an existing named event object,
this function requests the EVENT_ALL_ACCESS access right. In
this case, the bManualReset and bInitialState parameters are
ignored because they have already been set by the creating
process. If the lpEventAttributes parameter is not NULL, it
determines whether the handle can be inherited, but its
security-descriptor member is ignored.
If lpName is NULL, the event object is created without a name.
If lpName matches the name of another kind of object in the
same name space (such as an existing semaphore, mutex,
waitable timer, job, or file-mapping object), the function fails
and the GetLastError function returns
ERROR_INVALID_HANDLE. This occurs because these objects
share the same name space.
The name can have a "Global" or "Local" prefix to explicitly
create the object in the global or session name space. The
remainder of the name can contain any character except the
backslash character (). For more information, see Kernel
Object Namespaces. Fast user switching is implemented using
Terminal Services sessions. Kernel object names must follow
the guidelines outlined for Terminal Services so that
applications can support multiple users.
Windows 2000: If Terminal Services is not running, the
"Global" and "Local" prefixes are ignored. The remainder of
the name can contain any character except the backslash
character.
The object can be created in a private namespace. For more
information, see Object Namespaces.
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
Return Value
If the function succeeds, the return value is a handle to the event
object. If the named event object existed before the function call, the
function returns a handle to the existing object and GetLastError
returns ERROR_ALREADY_EXISTS.
If the function fails, the return value is NULL. To get extended error
information, call GetLastError.
Remarks
The handle returned by CreateEvent has the EVENT_ALL_ACCESS
access right; it can be used in any function that requires a handle to
an event object, provided that the caller has been granted access. If
an event is created from a service or a thread that is impersonating a
different user, you can either apply a security descriptor to the event
when you create it, or change the default security descriptor for the
creating process by changing its default DACL. For more information,
see Synchronization Object Security and Access Rights.
Any thread of the calling process can specify the event-object handle
in a call to one of the wait functions. The single-object wait functions
return when the state of the specified object is signaled. The
multiple-object wait functions can be instructed to return either when
any one or when all of the specified objects are signaled. When a wait
function returns, the waiting thread is released to continue its
execution.
The initial state of the event object is specified by the bInitialState
parameter. Use the SetEvent function to set the state of an event
object to signaled. Use the ResetEvent function to reset the state of
an event object to nonsignaled.
When the state of a manual-reset event object is signaled, it remains
signaled until it is explicitly reset to nonsignaled by the ResetEvent
function. Any number of waiting threads, or threads that
subsequently begin wait operations for the specified event object, can
be released while the object's state is signaled.
When the state of an auto-reset event object is signaled, it remains
signaled until a single waiting thread is released; the system then
automatically resets the state to nonsignaled. If no threads are
waiting, the event object's state remains signaled.
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
Multiple processes can have handles of the same event object,
enabling use of the object for interprocess synchronization. The
following object-sharing mechanisms are available:
• A child process created by the CreateProcess function can
inherit a handle to an event object if the lpEventAttributes
parameter of CreateEvent enabled inheritance.
• A process can specify the event-object handle in a call to the
DuplicateHandle function to create a duplicate handle that
can be used by another process.
• A process can specify the name of an event object in a call to the
OpenEvent or CreateEvent function.
Use the CloseHandle function to close the handle. The system closes
the handle automatically when the process terminates. The event
object is destroyed when its last handle has been closed.
Examples
For an example that uses CreateEvent, see Using Event Objects.
Requirements
Minimum supported
client
Windows 2000 Professional
Minimum supported
server
Windows 2000 Server
Header Winbase.h (include Windows.h)
Library Kernel32.lib
DLL Kernel32.dll
Unicode and ANSI
names
CreateEventW (Unicode) and
CreateEventA (ANSI)
See Also
CloseHandle
CreateEventEx
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
CreateProcess
DuplicateHandle
Event Objects
Object Names
OpenEvent
ResetEvent
SECURITY_ATTRIBUTES
SetEvent
Synchronization Functions
8.OpenEvent Function
Opens an existing named event object.
Syntax
C++
HANDLE WINAPI OpenEvent(
__in DWORD dwDesiredAccess,
__in BOOL bInheritHandle,
__in LPCTSTR lpName
);
Parameters
dwDesiredAccess [in]
The access to the event object. The function fails if the security descriptor of the specified object
does not permit the requested access for the calling process. For a list of access rights, see
Synchronization Object Security and Access Rights.
bInheritHandle [in]
If this value is TRUE, processes created by this process will inherit the handle. Otherwise, the
processes do not inherit this handle.
lpName [in]
The name of the event to be opened. Name comparisons are case sensitive.
This function can open objects in a private namespace. For more information, see Object
Namespaces.
Terminal Services: The name can have a "Global" or "Local" prefix to explicitly
open an object in the global or session name space. The remainder of the name can
contain any character except the backslash character (). For more information, see
Kernel Object Namespaces.
Windows XP Home Edition: Fast user switching is implemented using Terminal
Services sessions. The first user to log on uses session 0, the next user to log on uses
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
session 1, and so on. Kernel object names must follow the guidelines outlined for
Terminal Services so that applications can support multiple users.
Windows 2000: If Terminal Services is not running, the "Global" and "Local"
prefixes are ignored. The remainder of the name can contain any character except the
backslash character.
Return Value
If the function succeeds, the return value is a handle to the event object.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Remarks
The OpenEvent function enables multiple processes to open handles of the same event object. The
function succeeds only if some process has already created the event by using the CreateEvent function.
The calling process can use the returned handle in any function that requires a handle to an event object,
subject to the limitations of the access specified in the dwDesiredAccess parameter.
The handle can be duplicated by using the DuplicateHandle function. Use the CloseHandle function to
close the handle. The system closes the handle automatically when the process terminates. The event
object is destroyed when its last handle has been closed.
9 SetEvent Function
首先介绍 CreateEvent 是创建 windows 事件的意思,作用主要用在判
断线程退出,程锁定方面.
CreateEvent
函功能描述:创建或打开一个命名的或无名的事件对象.
EVENT 有两种状态:发信号,不发信号。
SetEvent/ResetEvent 分别将 EVENT 置为这两种状态分别是发信号与
不发信号。
WaitForSingleObject()等待,直到参数所指定的 OBJECT 成为发信
号状态时才返回,OBJECT 可以是 EVENT,也可以是其它内核对象。
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
当你创建一个线程时,其实那个线程是一个循环,不像上面那样只运
行一次的。这样就带来了一个问题,在那个死循环里要找到合适的条
件退出那个死循环,那么是怎么样实现它的呢?在 Windows 里往往
是采用事件的方式,当然还可以采用其它的方式。在这里先介绍采用
事件的方式来通知从线程运行函数退出来,它的实现原理是这样,在
那个死循环里不断地使用 WaitForSingleObject 函数来检查事件是否
满足,如果满足就退出线程,不满足就继续运行。当在线程里运行阻
塞的函数时,就需要在退出线程时,先要把阻塞状态变成非阻塞状态,
比如使用一个线程去接收网络数据,同时使用阻塞的 SOCKET 时,
那么要先关闭 SOCKET,再发送事件信号,才可以退出线程的。下面
就来演示怎么样使用事件来通知线程退出来。
Sets the specified event object to the signaled state.
Syntax
C++
BOOL WINAPI SetEvent(
__in HANDLE hEvent
);
Parameters
hEvent [in]
A handle to the event object. The CreateEvent or OpenEvent function returns this handle.
The handle must have the EVENT_MODIFY_STATE access right. For more information, see
Synchronization Object Security and Access Rights.
Return Value
If the function succeeds, the return value is nonzero.
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Remarks
The state of a manual-reset event object remains signaled until it is set explicitly to the nonsignaled state
by the ResetEvent function. Any number of waiting threads, or threads that subsequently begin wait
operations for the specified event object by calling one of the wait functions, can be released while the
object's state is signaled.
The state of an auto-reset event object remains signaled until a single waiting thread is released, at
which time the system automatically sets the state to nonsignaled. If no threads are waiting, the event
object's state remains signaled.
Setting an event that is already set has no effect.
Examples
10 ResetEvent Function
Sets the specified event object to the nonsignaled state.
Syntax
C++
BOOL WINAPI ResetEvent(
__in HANDLE hEvent
);
Parameters
hEvent [in]
A handle to the event object. The CreateEvent or OpenEvent function returns this handle.
The handle must have the EVENT_MODIFY_STATE access right. For more information, see
Synchronization Object Security and Access Rights.
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 state of an event object remains nonsignaled until it is explicitly set to signaled by the SetEvent or
PulseEvent function. This nonsignaled state blocks the execution of any threads that have specified the
event object in a call to one of the wait functions.
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
The ResetEvent function is used primarily for manual-reset event objects, which must be set explicitly
to the nonsignaled state. Auto-reset event objects automatically change from signaled to nonsignaled
after a single waiting thread is released.
Resetting an event that is already reset has no effect
11 PulseEvent Function
Sets the specified event object to the signaled state and then resets it to the nonsignaled state after
releasing the appropriate number of waiting threads.
Note This function is unreliable and should not be used. It exists mainly for backward compatibility. For
more information, see Remarks.
Syntax
C++
BOOL WINAPI PulseEvent(
__in HANDLE hEvent
);
Parameters
hEvent [in]
A handle to the event object. The CreateEvent or OpenEvent function returns this handle.
The handle must have the EVENT_MODIFY_STATE access right. For more information, see
Synchronization Object Security and Access Rights.
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
A thread waiting on a synchronization object can be momentarily removed from the wait state by a
kernel-mode APC, and then returned to the wait state after the APC is complete. If the call to PulseEvent
occurs during the time when the thread has been removed from the wait state, the thread will not be
released because PulseEvent releases only those threads that are waiting at the moment it is called.
Therefore, PulseEvent is unreliable and should not be used by new applications. Instead, use condition
variables.
For a manual-reset event object, all waiting threads that can be released immediately are released. The
function then resets the event object's state to nonsignaled and returns.
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
For an auto-reset event object, the function resets the state to nonsignaled and returns after releasing a
single waiting thread, even if multiple threads are waiting.
If no threads are waiting, or if no thread can be released immediately, PulseEvent simply sets the event
object's state to nonsignaled and returns.
Note that for a thread using the multiple-object wait functions to wait for all specified objects to be
signaled, PulseEvent can set the event object's state to signaled and reset it to nonsignaled without
causing the wait function to return. This happens if not all of the specified objects are simultaneously
signaled.
12 Creating Processes
The CreateProcess function creates a new process, which runs independently of the creating process.
However, for simplicity, the relationship is referred to as a parent-child relationship.
The following code demonstrates how to create a process.
Copy Code
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _tmain( int argc, TCHAR *argv[] )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( argc != 2 )
{
printf("Usage: %s [cmdline]n", argv[0]);
return;
}
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
argv[1], // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d).n", GetLastError() );
return;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
If CreateProcess succeeds, it returns a PROCESS_INFORMATION structure containing handles and
identifiers for the new process and its primary thread. The thread and process handles are created with
full access rights, although access can be restricted if you specify security descriptors. When you no
longer need these handles, close them by using the CloseHandle function.
You can also create a process using the CreateProcessAsUser or CreateProcessWithLogonW
function. This allows you to specify the security context of the user account in which the process will
execute.
13 WaitForSingleObject Function
Waits until the specified object is in the signaled state or the time-out interval elapses.
To enter an alertable wait state, use the WaitForSingleObjectEx function. To wait for multiple objects,
use the WaitForMultipleObjects.
Syntax
C++
DWORD WINAPI WaitForSingleObject(
__in HANDLE hHandle,
__in DWORD dwMilliseconds
);
Parameters
hHandle [in]
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
A handle to the object. For a list of the object types whose handles can be specified, see the
following Remarks section.
If this handle is closed while the wait is still pending, the function's behavior is undefined.
The handle must have the SYNCHRONIZE access right. For more information, see Standard
Access Rights.
dwMilliseconds [in]
The time-out interval, in milliseconds. If a nonzero value is specified, the function waits until the
object is signaled or the interval elapses. If dwMilliseconds is zero, the function does not enter
a wait state if the object is not signaled; it always returns immediately. If dwMilliseconds is
INFINITE, the function will return only when the object is signaled.
Return Value
If the function succeeds, the return value indicates the event that caused the function to return. It can be
one of the following values.
Return code/value Description
WAIT_ABANDONED
0x00000080L
The specified object is a mutex object that was not released by the thread
that owned the mutex object before the owning thread terminated.
Ownership of the mutex object is granted to the calling thread and the
mutex state is set to nonsignaled.
If the mutex was protecting persistent state information, you should check
it for consistency.
WAIT_OBJECT_0
0x00000000L
The state of the specified object is signaled.
WAIT_TIMEOUT
0x00000102L
The time-out interval elapsed, and the object's state is nonsignaled.
WAIT_FAILED
(DWORD)0xFFFFFFFF
The function has failed. To get extended error information, call
GetLastError.
Remarks
The WaitForSingleObject function checks the current state of the specified object. If the object's state
is nonsignaled, the calling thread enters the wait state until the object is signaled or the time-out interval
elapses.
The function modifies the state of some types of synchronization objects. Modification occurs only for the
object whose signaled state caused the function to return. For example, the count of a semaphore object
is decreased by one.
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
The WaitForSingleObject function can wait for the following objects:
• Change notification
• Console input
• Event
• Memory resource notification
• Mutex
• Process
• Semaphore
• Thread
• Waitable timer
Use caution when calling the wait functions and code that directly or indirectly creates windows. If a
thread creates any windows, it must process messages. Message broadcasts are sent to all windows in
the system. A thread that uses a wait function with no time-out interval may cause the system to become
deadlocked. Two examples of code that indirectly creates windows are DDE and the CoInitialize
function. Therefore, if you have a thread that creates windows, use MsgWaitForMultipleObjects or
MsgWaitForMultipleObjectsEx, rather than WaitForSingleObject.
Examples
For an example, see Using Mutex Objects.
Requirements
Minimum supported client Windows 2000 Professional
Minimum supported server Windows 2000 Server
Header Winbase.h (include Windows.h)
Library Kernel32.lib
DLL Kernel32.dll
See Also
14 HeapAlloc Function
Allocates a block of memory from a heap. The allocated memory is not movable.
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
Syntax
C++
LPVOID WINAPI HeapAlloc(
__in HANDLE hHeap,
__in DWORD dwFlags,
__in SIZE_T dwBytes
);
Parameters
hHeap [in]
A handle to the heap from which the memory will be allocated. This handle is returned by the
HeapCreate or GetProcessHeap function.
dwFlags [in]
The heap allocation options. Specifying any of these values will override the corresponding
value specified when the heap was created with HeapCreate. This parameter can be one or
more of the following values.
Value Meaning
HEAP_GENERATE_EXCEPTIONS
0x00000004
The system will raise an exception to indicate a function failure,
such as an out-of-memory condition, instead of returning NULL.
To ensure that exceptions are generated for all calls to this
function, specify HEAP_GENERATE_EXCEPTIONS in the call to
HeapCreate. In this case, it is not necessary to additionally
specify HEAP_GENERATE_EXCEPTIONS in this function call.
HEAP_NO_SERIALIZE
0x00000001
Serialized access will not be used for this allocation. For more
information, see Remarks.
To ensure that serialized access is disabled for all calls to this
function, specify HEAP_NO_SERIALIZE in the call to
HeapCreate. In this case, it is not necessary to additionally
specify HEAP_NO_SERIALIZE in this function call.
This value should not be specified when accessing the process's
default heap. The system may create additional threads within
the application's process, such as a CTRL+C handler, that
simultaneously access the process's default heap.
HEAP_ZERO_MEMORY
0x00000008
The allocated memory will be initialized to zero. Otherwise, the
memory is not initialized to zero.
dwBytes [in]
The number of bytes to be allocated.
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
If the heap specified by the hHeap parameter is a "non-growable" heap, dwBytes must be less
than 0x7FFF8. You create a non-growable heap by calling the HeapCreate function with a
nonzero value.
Return Value
If the function succeeds, the return value is a pointer to the allocated memory block.
If the function fails and you have not specified HEAP_GENERATE_EXCEPTIONS, the return value is NULL.
If the function fails and you have specified HEAP_GENERATE_EXCEPTIONS, the function may generate
either of the following exceptions. The particular exception depends upon the nature of the heap
corruption.
Return code Description
STATUS_NO_MEMORY The allocation attempt failed because of a lack of available memory
or heap corruption.
STATUS_ACCESS_VIOLATION The allocation attempt failed because of heap corruption or
improper function parameters.
If the function fails, it does not call SetLastError. An application cannot call GetLastError for extended
error information.
Remarks
If the HeapAlloc function succeeds, it allocates at least the amount of memory requested.
To allocate memory from the process's default heap, use HeapAlloc with the handle returned by the
GetProcessHeap function.
To free a block of memory allocated by HeapAlloc, use the HeapFree function.
Memory allocated by HeapAlloc is not movable. The address returned by HeapAlloc is valid until the
memory block is freed or reallocated; the memory block does not need to be locked. Because the system
cannot compact a private heap, it can become fragmented.
Applications that allocate large amounts of memory in various allocation sizes can use the
low-fragmentation heap to reduce heap fragmentation.
Serialization ensures mutual exclusion when two or more threads attempt to simultaneously allocate or
free blocks from the same heap. There is a small performance cost to serialization, but it must be used
whenever multiple threads allocate and free memory from the same heap. Setting the
HEAP_NO_SERIALIZE value eliminates mutual exclusion on the heap. Without serialization, two or more
threads that use the same heap handle might attempt to allocate or free memory simultaneously, likely
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
causing corruption in the heap. The HEAP_NO_SERIALIZE value can, therefore, be safely used only in the
following situations:
• The process has only one thread.
• The process has multiple threads, but only one thread calls the heap functions for a specific
heap.
• The process has multiple threads, and the application provides its own mechanism for mutual
exclusion to a specific heap.
15 LocalFree Function
Frees the specified local memory object and invalidates its handle.
Note The local functions have greater overhead and provide fewer features than other memory
management functions. New applications should use the heap functions unless documentation states
that a local function should be used. For more information, see Global and Local Functions.
Syntax
C++
HLOCAL WINAPI LocalFree(
__in HLOCAL hMem
);
Parameters
hMem [in]
A handle to the local memory object. This handle is returned by either the LocalAlloc or
LocalReAlloc function. It is not safe to free memory allocated with GlobalAlloc.
Return Value
If the function succeeds, the return value is NULL.
If the function fails, the return value is equal to a handle to the local memory object. To get extended
error information, call GetLastError.
Remarks
If the process tries to examine or modify the memory after it has been freed, heap corruption may occur
or an access violation exception (EXCEPTION_ACCESS_VIOLATION) may be generated.
If the hMem parameter is NULL, LocalFree ignores the parameter and returns NULL.
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
The LocalFree function will free a locked memory object. A locked memory object has a lock count
greater than zero. The LocalLock function locks a local memory object and increments the lock count by
one. The LocalUnlock function unlocks it and decrements the lock count by one. To get the lock count
of a local memory object, use the LocalFlags function.
If an application is running under a debug version of the system, LocalFree will issue a message that
tells you that a locked object is being freed. If you are debugging the application, LocalFree will enter a
breakpoint just before freeing a locked object. This allows you to verify the intended behavior, then
continue execution.
16 GetLastError Function
Retrieves the calling thread's last-error code value. The last-error code is maintained on a
per-thread basis. Multiple threads do not overwrite each other's last-error code.
Visual Basic: Applications should call err.LastDllError instead of GetLastError.
17.CreateProcess
This function is used to run a new program. It creates a new process and its primary thread. The
new process executes the specified executable file.
Note The remote application interface (RAPI) version of this function is named CeCreateProcess
(RAPI).
BOOL CreateProcess(
LPCWSTR pszImageName,
LPCWSTR pszCmdLine,
LPSECURITY_ATTRIBUTES psaProcess,
LPSECURITY_ATTRIBUTES psaThread,
BOOL fInheritHandles,
DWORD fdwCreate,
LPVOID pvEnvironment,
LPWSTR pszCurDir,
LPSTARTUPINFOW psiStartInfo,
LPPROCESS_INFORMATION pProcInfo
);
Parameters
pszImageName
[in] Pointer to a null-terminated string that specifies the module
to execute.
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
The string can specify the full path and filename of the module to
execute or it can specify a partial path and filename.
The lpszImageName parameter must be non-NULL and must include
the module name.
pszCmdLine
[in, out] Pointer to a null-terminated string that specifies the
command line to execute.
The system adds a null character to the command line, trimming the
string if necessary, to indicate which file was used.
The lpszCmdLine parameter can be NULL. In that case, the function
uses the string pointed to by lpszImageName as the command line.
If lpszImageName and lpszCmdLine are non-NULL, * lpszImageName
specifies the module to execute, and * lpszCmdLine specifies the
command line.
18 GetSystemTimeAsFileTime
Retrieves the current system date and time. The information is in Coordinated Universal Time
(UTC) format.
Syntax
C++
void WINAPI GetSystemTimeAsFileTime(
__out LPFILETIME lpSystemTimeAsFileTime
);
Parameters
lpSystemTimeAsFileTime [out]
A pointer to a FILETIME structure to receive the current system date and time in
UTC format.
Return Value
北京四元教育 http://www.bj111.cn
010-8956040,13691026331
This function does not return a value.
Requirements

More Related Content

What's hot

intro unix/linux 10
intro unix/linux 10intro unix/linux 10
intro unix/linux 10duquoi
 
Arp Dan Ipconfig Syntax
Arp Dan Ipconfig  SyntaxArp Dan Ipconfig  Syntax
Arp Dan Ipconfig Syntaxguestcc37e8c
 
intro unix/linux 04
intro unix/linux 04intro unix/linux 04
intro unix/linux 04duquoi
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
Distributed Queries in IDS: New features.
Distributed Queries in IDS: New features.Distributed Queries in IDS: New features.
Distributed Queries in IDS: New features.Keshav Murthy
 
Perly Parsing with Regexp::Grammars
Perly Parsing with Regexp::GrammarsPerly Parsing with Regexp::Grammars
Perly Parsing with Regexp::GrammarsWorkhorse Computing
 
LD_PRELOAD Exploitation - DC9723
LD_PRELOAD Exploitation - DC9723LD_PRELOAD Exploitation - DC9723
LD_PRELOAD Exploitation - DC9723Iftach Ian Amit
 
intro unix/linux 05
intro unix/linux 05intro unix/linux 05
intro unix/linux 05duquoi
 
Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Ivelin Yanev
 
Apache thrift-RPC service cross languages
Apache thrift-RPC service cross languagesApache thrift-RPC service cross languages
Apache thrift-RPC service cross languagesJimmy Lai
 
Language Resource Processing Configuration and Run
Language Resource Processing Configuration and RunLanguage Resource Processing Configuration and Run
Language Resource Processing Configuration and Runmario_munoz
 

What's hot (20)

intro unix/linux 10
intro unix/linux 10intro unix/linux 10
intro unix/linux 10
 
Arp Dan Ipconfig Syntax
Arp Dan Ipconfig  SyntaxArp Dan Ipconfig  Syntax
Arp Dan Ipconfig Syntax
 
intro unix/linux 04
intro unix/linux 04intro unix/linux 04
intro unix/linux 04
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Distributed Queries in IDS: New features.
Distributed Queries in IDS: New features.Distributed Queries in IDS: New features.
Distributed Queries in IDS: New features.
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Hadoop training-in-hyderabad
Hadoop training-in-hyderabadHadoop training-in-hyderabad
Hadoop training-in-hyderabad
 
Perly Parsing with Regexp::Grammars
Perly Parsing with Regexp::GrammarsPerly Parsing with Regexp::Grammars
Perly Parsing with Regexp::Grammars
 
C++11 Multithreading - Futures
C++11 Multithreading - FuturesC++11 Multithreading - Futures
C++11 Multithreading - Futures
 
Log4 J
Log4 JLog4 J
Log4 J
 
Curl
CurlCurl
Curl
 
LD_PRELOAD Exploitation - DC9723
LD_PRELOAD Exploitation - DC9723LD_PRELOAD Exploitation - DC9723
LD_PRELOAD Exploitation - DC9723
 
intro unix/linux 05
intro unix/linux 05intro unix/linux 05
intro unix/linux 05
 
Best Of Jdk 7
Best Of Jdk 7Best Of Jdk 7
Best Of Jdk 7
 
Log4j
Log4jLog4j
Log4j
 
Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11
 
Apache thrift-RPC service cross languages
Apache thrift-RPC service cross languagesApache thrift-RPC service cross languages
Apache thrift-RPC service cross languages
 
java networking
 java networking java networking
java networking
 
Language Resource Processing Configuration and Run
Language Resource Processing Configuration and RunLanguage Resource Processing Configuration and Run
Language Resource Processing Configuration and Run
 
Linux
LinuxLinux
Linux
 

Viewers also liked

Power point (trebalh de sintesis)
Power point (trebalh de sintesis)Power point (trebalh de sintesis)
Power point (trebalh de sintesis)competic
 
SMi Group's 4th annual Military Flight Training 2015 conference
SMi Group's 4th annual Military Flight Training 2015 conferenceSMi Group's 4th annual Military Flight Training 2015 conference
SMi Group's 4th annual Military Flight Training 2015 conferenceDale Butler
 
App Measurement for mCommerce
App Measurement for mCommerceApp Measurement for mCommerce
App Measurement for mCommerceJim Nichols
 
مجد السماعيل . هرم خوفو
مجد السماعيل . هرم خوفومجد السماعيل . هرم خوفو
مجد السماعيل . هرم خوفوhusseinw
 

Viewers also liked (10)

BPLTravel
BPLTravelBPLTravel
BPLTravel
 
Power point (trebalh de sintesis)
Power point (trebalh de sintesis)Power point (trebalh de sintesis)
Power point (trebalh de sintesis)
 
Gfgfghtyf
GfgfghtyfGfgfghtyf
Gfgfghtyf
 
Isla Primera Residencial
Isla Primera ResidencialIsla Primera Residencial
Isla Primera Residencial
 
SMi Group's 4th annual Military Flight Training 2015 conference
SMi Group's 4th annual Military Flight Training 2015 conferenceSMi Group's 4th annual Military Flight Training 2015 conference
SMi Group's 4th annual Military Flight Training 2015 conference
 
Buckingham palace
Buckingham palaceBuckingham palace
Buckingham palace
 
Anova dua jalur
Anova dua jalurAnova dua jalur
Anova dua jalur
 
PhD Defense
PhD DefensePhD Defense
PhD Defense
 
App Measurement for mCommerce
App Measurement for mCommerceApp Measurement for mCommerce
App Measurement for mCommerce
 
مجد السماعيل . هرم خوفو
مجد السماعيل . هرم خوفومجد السماعيل . هرم خوفو
مجد السماعيل . هرم خوفو
 

Similar to API

Copper: A high performance workflow engine
Copper: A high performance workflow engineCopper: A high performance workflow engine
Copper: A high performance workflow enginedmoebius
 
Chapter Seven(2)
Chapter Seven(2)Chapter Seven(2)
Chapter Seven(2)bolovv
 
Nov. 4, 2011 o reilly webcast-hbase- lars george
Nov. 4, 2011 o reilly webcast-hbase- lars georgeNov. 4, 2011 o reilly webcast-hbase- lars george
Nov. 4, 2011 o reilly webcast-hbase- lars georgeO'Reilly Media
 
Examples from Pune meetup
Examples from Pune meetupExamples from Pune meetup
Examples from Pune meetupSantosh Ojha
 
Chapter Seven(1)
Chapter Seven(1)Chapter Seven(1)
Chapter Seven(1)bolovv
 
Sedna XML Database: Executor Internals
Sedna XML Database: Executor InternalsSedna XML Database: Executor Internals
Sedna XML Database: Executor InternalsIvan Shcheklein
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streamingphanleson
 
Buffer overflow tutorial
Buffer overflow tutorialBuffer overflow tutorial
Buffer overflow tutorialhughpearse
 
Performance Teting - VU Scripting Using Rational (http://www.geektester.blogs...
Performance Teting - VU Scripting Using Rational (http://www.geektester.blogs...Performance Teting - VU Scripting Using Rational (http://www.geektester.blogs...
Performance Teting - VU Scripting Using Rational (http://www.geektester.blogs...raj.kamal13
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsFulvio Corno
 
Cassandra 2.1 boot camp, Overview
Cassandra 2.1 boot camp, OverviewCassandra 2.1 boot camp, Overview
Cassandra 2.1 boot camp, OverviewJoshua McKenzie
 
Tips
TipsTips
Tipsmclee
 
Intermediate code optimization Unit-4.pdf
Intermediate code optimization Unit-4.pdfIntermediate code optimization Unit-4.pdf
Intermediate code optimization Unit-4.pdfHimanshu883663
 
apache-refcard-a4.pdf
apache-refcard-a4.pdfapache-refcard-a4.pdf
apache-refcard-a4.pdfGiovaRossi
 

Similar to API (20)

Copper: A high performance workflow engine
Copper: A high performance workflow engineCopper: A high performance workflow engine
Copper: A high performance workflow engine
 
Chapter Seven(2)
Chapter Seven(2)Chapter Seven(2)
Chapter Seven(2)
 
Nov. 4, 2011 o reilly webcast-hbase- lars george
Nov. 4, 2011 o reilly webcast-hbase- lars georgeNov. 4, 2011 o reilly webcast-hbase- lars george
Nov. 4, 2011 o reilly webcast-hbase- lars george
 
Examples from Pune meetup
Examples from Pune meetupExamples from Pune meetup
Examples from Pune meetup
 
Chapter Seven(1)
Chapter Seven(1)Chapter Seven(1)
Chapter Seven(1)
 
Sedna XML Database: Executor Internals
Sedna XML Database: Executor InternalsSedna XML Database: Executor Internals
Sedna XML Database: Executor Internals
 
SCDJWS 5. JAX-WS
SCDJWS 5. JAX-WSSCDJWS 5. JAX-WS
SCDJWS 5. JAX-WS
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streaming
 
Srgoc dotnet
Srgoc dotnetSrgoc dotnet
Srgoc dotnet
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Buffer overflow tutorial
Buffer overflow tutorialBuffer overflow tutorial
Buffer overflow tutorial
 
Performance Teting - VU Scripting Using Rational (http://www.geektester.blogs...
Performance Teting - VU Scripting Using Rational (http://www.geektester.blogs...Performance Teting - VU Scripting Using Rational (http://www.geektester.blogs...
Performance Teting - VU Scripting Using Rational (http://www.geektester.blogs...
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Cassandra 2.1 boot camp, Overview
Cassandra 2.1 boot camp, OverviewCassandra 2.1 boot camp, Overview
Cassandra 2.1 boot camp, Overview
 
Tips
TipsTips
Tips
 
Database programming
Database programmingDatabase programming
Database programming
 
Intermediate code optimization Unit-4.pdf
Intermediate code optimization Unit-4.pdfIntermediate code optimization Unit-4.pdf
Intermediate code optimization Unit-4.pdf
 
apache-refcard-a4.pdf
apache-refcard-a4.pdfapache-refcard-a4.pdf
apache-refcard-a4.pdf
 

Recently uploaded

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Recently uploaded (20)

Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

API

  • 1. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 常用的 API 函数 1.ProcessIdToSessionId Function Retrieves the Remote Desktop Services session associated with a specified process. Syntax C++ BOOL ProcessIdToSessionId( __in DWORD dwProcessId, __out DWORD *pSessionId ); Parameters dwProcessId [in] Specifies a process identifier. Use the GetCurrentProcessId function to retrieve the process identifier for the current process. pSessionId [out] Pointer to a variable that receives the identifier of the Remote Desktop Services session under which the specified process is running. To retrieve the identifier of the session currently attached to the console, use the WTSGetActiveConsoleSessionId function. Return Value If the function succeeds, the return value is a nonzero value. If the function fails, the return value is zero. To get extended error information, call GetLastError. Remarks Callers must hold the PROCESS_QUERY_INFORMATION access right for the specified process. For more information, see Process Security and Access Rights. Requirements
  • 2. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 Minimum supported client Windows 2000 Professional Minimum supported server Windows 2000 Server Header Winbase.h (include Windows.h) Library Kernel32.lib DLL Kernel32.dll
  • 3. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 2.GetCurrentDirectory Function Retrieves the current directory for the current process. Syntax C++ DWORD WINAPI GetCurrentDirectory( __in DWORD nBufferLength, __out LPTSTR lpBuffer ); Parameters nBufferLength [in] The length of the buffer for the current directory string, in TCHARs. The buffer length must include room for a terminating null character. lpBuffer [out] A pointer to the buffer that receives the current directory string. This null-terminated string specifies the absolute path to the current directory. To determine the required buffer size, set this parameter to NULL and the nBufferLength parameter to 0. Return Value If the function succeeds, the return value specifies the number of characters that are written to the buffer, not including the terminating null character. If the function fails, the return value is zero. To get extended error information, call GetLastError. If the buffer that is pointed to by lpBuffer is not large enough, the return value specifies the required size of the buffer, in characters, including the null-terminating character. Remarks Each process has a single current directory that consists of two parts:
  • 4. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 • A disk designator that is either a drive letter followed by a colon, or a server name followed by a share name (servernamesharename) • A directory on the disk designator To set the current directory, use the SetCurrentDirectory function. Multithreaded applications and shared library code should not use the GetCurrentDirectory function and should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. This limitation also applies to the SetCurrentDirectory and GetFullPathName functions. The exception being when the application is guaranteed to be running in a single thread, for example parsing file names from the command line argument string in the main thread prior to creating any additional threads. Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported. Examples For an example, see Changing the Current Directory. Requirements Minimum supported client Windows 2000 Professional Minimum supported server Windows 2000 Server Header WinBase.h (include Windows.h) Library Kernel32.lib DLL Kernel32.dll Unicode and ANSI names GetCurrentDirectoryW (Unicode) and GetCurrentDirectoryA (ANSI)
  • 5. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 3. SetCurrentDirectory C++ BOOL WINAPI SetCurrentDirectory( __in LPCTSTR lpPathName ); Parameters lpPathName [in] The path to the new current directory. This parameter may specify a relative path or a full path. In either case, the full path of the specified directory is calculated and stored as the current directory. For more information, see File Names, Paths, and Namespaces. The string must not exceed MAX_PATH characters, including the terminating null character. The final character before the null character must be a backslash (''). If you do not specify the backslash, it will be added for you; therefore, specify MAX_PATH-2 characters for the path unless you include the trailing backslash, in which case, specify MAX_PATH-1 characters for the path. 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 Each process has a single current directory made up of two parts: • A disk designator that is either a drive letter followed by a colon, or a server name and share name (servernamesharename) • A directory on the disk designator Multithreaded applications and shared library code should not use the SetCurrentDirectory function and should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, therefore multithreaded applications cannot reliably use this
  • 6. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 value without possible data corruption from other threads that may also be reading or setting this value. This limitation also applies to the GetCurrentDirectory and GetFullPathName functions. The exception being when the application is guaranteed to be running in a single thread, for example parsing file names from the command line argument string in the main thread prior to creating any additional threads. Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported. Examples For an example, see Changing the Current Directory. Requirements Minimum supported client Windows 2000 Professional Minimum supported server Windows 2000 Server Header WinBase.h (include Windows.h) Library Kernel32.lib DLL Kernel32.dll Unicode and ANSI names SetCurrentDirectoryW (Unicode) and SetCurrentDirectoryA (ANSI)
  • 7. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 4. Gets char *gets( char *buffer ); wchar_t *_getws( wchar_t *buffer ); Parameter buffer Storage location for input string. Return Value Returns its argument if successful. A NULL pointer indicates an error or end-of-file condition. Use ferror or feof to determine which one has occurred. Remarks The gets function reads a line from the standard input stream stdin and stores it in buffer. The line consists of all characters up to and including the first newline character ('n'). gets then replaces the newline character with a null character ('0') before returning the line. In contrast, the fgets function retains the newline character. _getws is a wide-character version of gets; its argument and return value are wide-character strings. Security Note Because there is no way to limit the number of characters read by gets, untrusted input can easily cause buffer overruns. Use fgets instead. Generic-Text Routine Mappings TCHAR.H routine _UNICODE & _MBCS not defined _MBCS defined _UNICODE defined _getts gets gets _getws
  • 8. 北京四元教育 http://www.bj111.cn Requirements Routine Required header Compatibility gets <stdio.h> ANSI, Win 98, Win Me, Win NT, Win 2000, Win XP _getws <stdio.h> or <wchar.h> ANSI, Win 98, Win Me, Win NT, Win 2000, Win XP For additional compatibility information, see Compatibility in the Introduction. 5 .MEMSET void *memset( void *dest, int c, size_t count ); wchar_t *wmemset( wchar_t *dest, wchar_t c, size_t count ); Parameters dest Pointer to destination. c Character to set. count Number of characters. Return Value The value of dest. Remarks Sets the first count characters of dest to the character c. Security Note Make sure that the destination buffer has enough room for at least count characters. For more information, see Avoiding Buffer Overruns. Requirements 010-8956040,13691026331
  • 9. 北京四元教育 http://www.bj111.cn Routine Required header memset <memory.h> or <string.h> wmemset <wchar.h> For additional compatibility information, see Compatibility in the Introduction. Libraries All versions of the C run-time libraries. Example Copy Code // crt_memset.c /* This program uses memset to * set the first four chars of buffer to "*". */ #include <memory.h> #include <stdio.h> int main( void ) { char buffer[] = "This is a test of the memset function"; printf( "Before: %sn", buffer ); memset( buffer, '*', 4 ); printf( "After: %sn", buffer ); } Output Before: This is a test of the memset function After: **** is a test of the memset function 010-8956040,13691026331
  • 10. 北京四元教育 http://www.bj111.cn 6. fread Reads data from a stream. size_t fread( void *buffer, size_t size, size_t count, FILE *stream ); Parameters buffer Storage location for data. size Item size in bytes. count Maximum number of items to be read. stream Pointer to FILE structure. Return Value fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count. Use the feof or ferror function to distinguish a read error from an end-of-file condition. If size or count is 0, fread returns 0 and the buffer contents are unchanged. If stream or buffer is a null pointer, fread invokes the invalid parameter handler, as described in Parameter Validation. If execution is allowed to continue, this function sets errno to EINVAL and returns 0. See _doserrno, errno, _sys_errlist, and _sys_nerr for more information on these, and other, error codes. Remarks The fread function reads up to count items of size bytes from the input stream and stores them in buffer. The file pointer associated with stream (if there is one) is increased by the number of bytes actually read. If the given stream is opened in text mode, carriage return–linefeed pairs are replaced with single linefeed characters. The replacement has no effect on the file pointer or the return value. The file-pointer position is indeterminate if an error occurs. The value of a partially read item cannot be determined. 010-8956040,13691026331
  • 11. 北京四元教育 http://www.bj111.cn This function locks out other threads. If you need a non-locking version, use _fread_nolock. Requirements Function Required header fread <stdio.h> For additional compatibility information, see Compatibility in the Introduction. Example Copy Code // crt_fread.c // This program opens a file named FREAD.OUT and // writes 25 characters to the file. It then tries to open // FREAD.OUT and read in 25 characters. If the attempt succeeds, // the program displays the number of actual items read. #include <stdio.h> int main( void ) { FILE *stream; char list[30]; int i, numread, numwritten; // Open file in text mode: if( fopen_s( &stream, "fread.out", "w+t" ) == 0 ) { for ( i = 0; i < 25; i++ ) list[i] = (char)('z' - i); // Write 25 characters to stream numwritten = fwrite( list, sizeof( char ), 25, stream ); printf( "Wrote %d itemsn", numwritten ); fclose( stream ); } else printf( "Problem opening the filen" ); if( fopen_s( &stream, "fread.out", "r+t" ) == 0 ) { // Attempt to read in 25 characters numread = fread( list, sizeof( char ), 25, stream ); 010-8956040,13691026331
  • 12. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 printf( "Number of items read = %dn", numread ); printf( "Contents of buffer = %.25sn", list ); fclose( stream ); } else printf( "File could not be openedn" ); } Copy Code Wrote 25 items Number of items read = 25 Contents of buffer = zyxwvutsrqponmlkjihgfedcb 7. CreateEvent Function Creates or opens a named or unnamed event object. To specify an access mask for the object, use the CreateEventEx function. Syntax C++ HANDLE WINAPI CreateEvent( __in_opt LPSECURITY_ATTRIBUTES lpEventAttributes, __in BOOL bManualReset, __in BOOL bInitialState, __in_opt LPCTSTR lpName ); Parameters lpEventAttributes [in, optional] A pointer to a SECURITY_ATTRIBUTES structure. If this parameter is NULL, the handle cannot be inherited by child processes. The lpSecurityDescriptor member of the structure specifies a security descriptor for the new event. If lpEventAttributes is NULL, the event gets a default security descriptor. The ACLs in the default security descriptor for an event come from the primary or impersonation token of the creator. bManualReset [in]
  • 13. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 If this parameter is TRUE, the function creates a manual-reset event object, which requires the use of the ResetEvent function to set the event state to nonsignaled. If this parameter is FALSE, the function creates an auto-reset event object, and system automatically resets the event state to nonsignaled after a single waiting thread has been released. bInitialState [in] If this parameter is TRUE, the initial state of the event object is signaled; otherwise, it is nonsignaled. lpName [in, optional] The name of the event object. The name is limited to MAX_PATH characters. Name comparison is case sensitive. If lpName matches the name of an existing named event object, this function requests the EVENT_ALL_ACCESS access right. In this case, the bManualReset and bInitialState parameters are ignored because they have already been set by the creating process. If the lpEventAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored. If lpName is NULL, the event object is created without a name. If lpName matches the name of another kind of object in the same name space (such as an existing semaphore, mutex, waitable timer, job, or file-mapping object), the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same name space. The name can have a "Global" or "Local" prefix to explicitly create the object in the global or session name space. The remainder of the name can contain any character except the backslash character (). For more information, see Kernel Object Namespaces. Fast user switching is implemented using Terminal Services sessions. Kernel object names must follow the guidelines outlined for Terminal Services so that applications can support multiple users. Windows 2000: If Terminal Services is not running, the "Global" and "Local" prefixes are ignored. The remainder of the name can contain any character except the backslash character. The object can be created in a private namespace. For more information, see Object Namespaces.
  • 14. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 Return Value If the function succeeds, the return value is a handle to the event object. If the named event object existed before the function call, the function returns a handle to the existing object and GetLastError returns ERROR_ALREADY_EXISTS. If the function fails, the return value is NULL. To get extended error information, call GetLastError. Remarks The handle returned by CreateEvent has the EVENT_ALL_ACCESS access right; it can be used in any function that requires a handle to an event object, provided that the caller has been granted access. If an event is created from a service or a thread that is impersonating a different user, you can either apply a security descriptor to the event when you create it, or change the default security descriptor for the creating process by changing its default DACL. For more information, see Synchronization Object Security and Access Rights. Any thread of the calling process can specify the event-object handle in a call to one of the wait functions. The single-object wait functions return when the state of the specified object is signaled. The multiple-object wait functions can be instructed to return either when any one or when all of the specified objects are signaled. When a wait function returns, the waiting thread is released to continue its execution. The initial state of the event object is specified by the bInitialState parameter. Use the SetEvent function to set the state of an event object to signaled. Use the ResetEvent function to reset the state of an event object to nonsignaled. When the state of a manual-reset event object is signaled, it remains signaled until it is explicitly reset to nonsignaled by the ResetEvent function. Any number of waiting threads, or threads that subsequently begin wait operations for the specified event object, can be released while the object's state is signaled. When the state of an auto-reset event object is signaled, it remains signaled until a single waiting thread is released; the system then automatically resets the state to nonsignaled. If no threads are waiting, the event object's state remains signaled.
  • 15. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 Multiple processes can have handles of the same event object, enabling use of the object for interprocess synchronization. The following object-sharing mechanisms are available: • A child process created by the CreateProcess function can inherit a handle to an event object if the lpEventAttributes parameter of CreateEvent enabled inheritance. • A process can specify the event-object handle in a call to the DuplicateHandle function to create a duplicate handle that can be used by another process. • A process can specify the name of an event object in a call to the OpenEvent or CreateEvent function. Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The event object is destroyed when its last handle has been closed. Examples For an example that uses CreateEvent, see Using Event Objects. Requirements Minimum supported client Windows 2000 Professional Minimum supported server Windows 2000 Server Header Winbase.h (include Windows.h) Library Kernel32.lib DLL Kernel32.dll Unicode and ANSI names CreateEventW (Unicode) and CreateEventA (ANSI) See Also CloseHandle CreateEventEx
  • 16. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 CreateProcess DuplicateHandle Event Objects Object Names OpenEvent ResetEvent SECURITY_ATTRIBUTES SetEvent Synchronization Functions 8.OpenEvent Function Opens an existing named event object. Syntax C++ HANDLE WINAPI OpenEvent( __in DWORD dwDesiredAccess, __in BOOL bInheritHandle, __in LPCTSTR lpName ); Parameters dwDesiredAccess [in] The access to the event object. The function fails if the security descriptor of the specified object does not permit the requested access for the calling process. For a list of access rights, see Synchronization Object Security and Access Rights. bInheritHandle [in] If this value is TRUE, processes created by this process will inherit the handle. Otherwise, the processes do not inherit this handle. lpName [in] The name of the event to be opened. Name comparisons are case sensitive. This function can open objects in a private namespace. For more information, see Object Namespaces. Terminal Services: The name can have a "Global" or "Local" prefix to explicitly open an object in the global or session name space. The remainder of the name can contain any character except the backslash character (). For more information, see Kernel Object Namespaces. Windows XP Home Edition: Fast user switching is implemented using Terminal Services sessions. The first user to log on uses session 0, the next user to log on uses
  • 17. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 session 1, and so on. Kernel object names must follow the guidelines outlined for Terminal Services so that applications can support multiple users. Windows 2000: If Terminal Services is not running, the "Global" and "Local" prefixes are ignored. The remainder of the name can contain any character except the backslash character. Return Value If the function succeeds, the return value is a handle to the event object. If the function fails, the return value is NULL. To get extended error information, call GetLastError. Remarks The OpenEvent function enables multiple processes to open handles of the same event object. The function succeeds only if some process has already created the event by using the CreateEvent function. The calling process can use the returned handle in any function that requires a handle to an event object, subject to the limitations of the access specified in the dwDesiredAccess parameter. The handle can be duplicated by using the DuplicateHandle function. Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The event object is destroyed when its last handle has been closed. 9 SetEvent Function 首先介绍 CreateEvent 是创建 windows 事件的意思,作用主要用在判 断线程退出,程锁定方面. CreateEvent 函功能描述:创建或打开一个命名的或无名的事件对象. EVENT 有两种状态:发信号,不发信号。 SetEvent/ResetEvent 分别将 EVENT 置为这两种状态分别是发信号与 不发信号。 WaitForSingleObject()等待,直到参数所指定的 OBJECT 成为发信 号状态时才返回,OBJECT 可以是 EVENT,也可以是其它内核对象。
  • 18. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 当你创建一个线程时,其实那个线程是一个循环,不像上面那样只运 行一次的。这样就带来了一个问题,在那个死循环里要找到合适的条 件退出那个死循环,那么是怎么样实现它的呢?在 Windows 里往往 是采用事件的方式,当然还可以采用其它的方式。在这里先介绍采用 事件的方式来通知从线程运行函数退出来,它的实现原理是这样,在 那个死循环里不断地使用 WaitForSingleObject 函数来检查事件是否 满足,如果满足就退出线程,不满足就继续运行。当在线程里运行阻 塞的函数时,就需要在退出线程时,先要把阻塞状态变成非阻塞状态, 比如使用一个线程去接收网络数据,同时使用阻塞的 SOCKET 时, 那么要先关闭 SOCKET,再发送事件信号,才可以退出线程的。下面 就来演示怎么样使用事件来通知线程退出来。 Sets the specified event object to the signaled state. Syntax C++ BOOL WINAPI SetEvent( __in HANDLE hEvent ); Parameters hEvent [in] A handle to the event object. The CreateEvent or OpenEvent function returns this handle. The handle must have the EVENT_MODIFY_STATE access right. For more information, see Synchronization Object Security and Access Rights. Return Value If the function succeeds, the return value is nonzero.
  • 19. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 If the function fails, the return value is zero. To get extended error information, call GetLastError. Remarks The state of a manual-reset event object remains signaled until it is set explicitly to the nonsignaled state by the ResetEvent function. Any number of waiting threads, or threads that subsequently begin wait operations for the specified event object by calling one of the wait functions, can be released while the object's state is signaled. The state of an auto-reset event object remains signaled until a single waiting thread is released, at which time the system automatically sets the state to nonsignaled. If no threads are waiting, the event object's state remains signaled. Setting an event that is already set has no effect. Examples 10 ResetEvent Function Sets the specified event object to the nonsignaled state. Syntax C++ BOOL WINAPI ResetEvent( __in HANDLE hEvent ); Parameters hEvent [in] A handle to the event object. The CreateEvent or OpenEvent function returns this handle. The handle must have the EVENT_MODIFY_STATE access right. For more information, see Synchronization Object Security and Access Rights. 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 state of an event object remains nonsignaled until it is explicitly set to signaled by the SetEvent or PulseEvent function. This nonsignaled state blocks the execution of any threads that have specified the event object in a call to one of the wait functions.
  • 20. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 The ResetEvent function is used primarily for manual-reset event objects, which must be set explicitly to the nonsignaled state. Auto-reset event objects automatically change from signaled to nonsignaled after a single waiting thread is released. Resetting an event that is already reset has no effect 11 PulseEvent Function Sets the specified event object to the signaled state and then resets it to the nonsignaled state after releasing the appropriate number of waiting threads. Note This function is unreliable and should not be used. It exists mainly for backward compatibility. For more information, see Remarks. Syntax C++ BOOL WINAPI PulseEvent( __in HANDLE hEvent ); Parameters hEvent [in] A handle to the event object. The CreateEvent or OpenEvent function returns this handle. The handle must have the EVENT_MODIFY_STATE access right. For more information, see Synchronization Object Security and Access Rights. 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 A thread waiting on a synchronization object can be momentarily removed from the wait state by a kernel-mode APC, and then returned to the wait state after the APC is complete. If the call to PulseEvent occurs during the time when the thread has been removed from the wait state, the thread will not be released because PulseEvent releases only those threads that are waiting at the moment it is called. Therefore, PulseEvent is unreliable and should not be used by new applications. Instead, use condition variables. For a manual-reset event object, all waiting threads that can be released immediately are released. The function then resets the event object's state to nonsignaled and returns.
  • 21. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 For an auto-reset event object, the function resets the state to nonsignaled and returns after releasing a single waiting thread, even if multiple threads are waiting. If no threads are waiting, or if no thread can be released immediately, PulseEvent simply sets the event object's state to nonsignaled and returns. Note that for a thread using the multiple-object wait functions to wait for all specified objects to be signaled, PulseEvent can set the event object's state to signaled and reset it to nonsignaled without causing the wait function to return. This happens if not all of the specified objects are simultaneously signaled. 12 Creating Processes The CreateProcess function creates a new process, which runs independently of the creating process. However, for simplicity, the relationship is referred to as a parent-child relationship. The following code demonstrates how to create a process. Copy Code #include <windows.h> #include <stdio.h> #include <tchar.h> void _tmain( int argc, TCHAR *argv[] ) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); if( argc != 2 ) { printf("Usage: %s [cmdline]n", argv[0]); return; } // Start the child process. if( !CreateProcess( NULL, // No module name (use command line) argv[1], // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE
  • 22. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) { printf( "CreateProcess failed (%d).n", GetLastError() ); return; } // Wait until child process exits. WaitForSingleObject( pi.hProcess, INFINITE ); // Close process and thread handles. CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); } If CreateProcess succeeds, it returns a PROCESS_INFORMATION structure containing handles and identifiers for the new process and its primary thread. The thread and process handles are created with full access rights, although access can be restricted if you specify security descriptors. When you no longer need these handles, close them by using the CloseHandle function. You can also create a process using the CreateProcessAsUser or CreateProcessWithLogonW function. This allows you to specify the security context of the user account in which the process will execute. 13 WaitForSingleObject Function Waits until the specified object is in the signaled state or the time-out interval elapses. To enter an alertable wait state, use the WaitForSingleObjectEx function. To wait for multiple objects, use the WaitForMultipleObjects. Syntax C++ DWORD WINAPI WaitForSingleObject( __in HANDLE hHandle, __in DWORD dwMilliseconds ); Parameters hHandle [in]
  • 23. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 A handle to the object. For a list of the object types whose handles can be specified, see the following Remarks section. If this handle is closed while the wait is still pending, the function's behavior is undefined. The handle must have the SYNCHRONIZE access right. For more information, see Standard Access Rights. dwMilliseconds [in] The time-out interval, in milliseconds. If a nonzero value is specified, the function waits until the object is signaled or the interval elapses. If dwMilliseconds is zero, the function does not enter a wait state if the object is not signaled; it always returns immediately. If dwMilliseconds is INFINITE, the function will return only when the object is signaled. Return Value If the function succeeds, the return value indicates the event that caused the function to return. It can be one of the following values. Return code/value Description WAIT_ABANDONED 0x00000080L The specified object is a mutex object that was not released by the thread that owned the mutex object before the owning thread terminated. Ownership of the mutex object is granted to the calling thread and the mutex state is set to nonsignaled. If the mutex was protecting persistent state information, you should check it for consistency. WAIT_OBJECT_0 0x00000000L The state of the specified object is signaled. WAIT_TIMEOUT 0x00000102L The time-out interval elapsed, and the object's state is nonsignaled. WAIT_FAILED (DWORD)0xFFFFFFFF The function has failed. To get extended error information, call GetLastError. Remarks The WaitForSingleObject function checks the current state of the specified object. If the object's state is nonsignaled, the calling thread enters the wait state until the object is signaled or the time-out interval elapses. The function modifies the state of some types of synchronization objects. Modification occurs only for the object whose signaled state caused the function to return. For example, the count of a semaphore object is decreased by one.
  • 24. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 The WaitForSingleObject function can wait for the following objects: • Change notification • Console input • Event • Memory resource notification • Mutex • Process • Semaphore • Thread • Waitable timer Use caution when calling the wait functions and code that directly or indirectly creates windows. If a thread creates any windows, it must process messages. Message broadcasts are sent to all windows in the system. A thread that uses a wait function with no time-out interval may cause the system to become deadlocked. Two examples of code that indirectly creates windows are DDE and the CoInitialize function. Therefore, if you have a thread that creates windows, use MsgWaitForMultipleObjects or MsgWaitForMultipleObjectsEx, rather than WaitForSingleObject. Examples For an example, see Using Mutex Objects. Requirements Minimum supported client Windows 2000 Professional Minimum supported server Windows 2000 Server Header Winbase.h (include Windows.h) Library Kernel32.lib DLL Kernel32.dll See Also 14 HeapAlloc Function Allocates a block of memory from a heap. The allocated memory is not movable.
  • 25. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 Syntax C++ LPVOID WINAPI HeapAlloc( __in HANDLE hHeap, __in DWORD dwFlags, __in SIZE_T dwBytes ); Parameters hHeap [in] A handle to the heap from which the memory will be allocated. This handle is returned by the HeapCreate or GetProcessHeap function. dwFlags [in] The heap allocation options. Specifying any of these values will override the corresponding value specified when the heap was created with HeapCreate. This parameter can be one or more of the following values. Value Meaning HEAP_GENERATE_EXCEPTIONS 0x00000004 The system will raise an exception to indicate a function failure, such as an out-of-memory condition, instead of returning NULL. To ensure that exceptions are generated for all calls to this function, specify HEAP_GENERATE_EXCEPTIONS in the call to HeapCreate. In this case, it is not necessary to additionally specify HEAP_GENERATE_EXCEPTIONS in this function call. HEAP_NO_SERIALIZE 0x00000001 Serialized access will not be used for this allocation. For more information, see Remarks. To ensure that serialized access is disabled for all calls to this function, specify HEAP_NO_SERIALIZE in the call to HeapCreate. In this case, it is not necessary to additionally specify HEAP_NO_SERIALIZE in this function call. This value should not be specified when accessing the process's default heap. The system may create additional threads within the application's process, such as a CTRL+C handler, that simultaneously access the process's default heap. HEAP_ZERO_MEMORY 0x00000008 The allocated memory will be initialized to zero. Otherwise, the memory is not initialized to zero. dwBytes [in] The number of bytes to be allocated.
  • 26. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 If the heap specified by the hHeap parameter is a "non-growable" heap, dwBytes must be less than 0x7FFF8. You create a non-growable heap by calling the HeapCreate function with a nonzero value. Return Value If the function succeeds, the return value is a pointer to the allocated memory block. If the function fails and you have not specified HEAP_GENERATE_EXCEPTIONS, the return value is NULL. If the function fails and you have specified HEAP_GENERATE_EXCEPTIONS, the function may generate either of the following exceptions. The particular exception depends upon the nature of the heap corruption. Return code Description STATUS_NO_MEMORY The allocation attempt failed because of a lack of available memory or heap corruption. STATUS_ACCESS_VIOLATION The allocation attempt failed because of heap corruption or improper function parameters. If the function fails, it does not call SetLastError. An application cannot call GetLastError for extended error information. Remarks If the HeapAlloc function succeeds, it allocates at least the amount of memory requested. To allocate memory from the process's default heap, use HeapAlloc with the handle returned by the GetProcessHeap function. To free a block of memory allocated by HeapAlloc, use the HeapFree function. Memory allocated by HeapAlloc is not movable. The address returned by HeapAlloc is valid until the memory block is freed or reallocated; the memory block does not need to be locked. Because the system cannot compact a private heap, it can become fragmented. Applications that allocate large amounts of memory in various allocation sizes can use the low-fragmentation heap to reduce heap fragmentation. Serialization ensures mutual exclusion when two or more threads attempt to simultaneously allocate or free blocks from the same heap. There is a small performance cost to serialization, but it must be used whenever multiple threads allocate and free memory from the same heap. Setting the HEAP_NO_SERIALIZE value eliminates mutual exclusion on the heap. Without serialization, two or more threads that use the same heap handle might attempt to allocate or free memory simultaneously, likely
  • 27. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 causing corruption in the heap. The HEAP_NO_SERIALIZE value can, therefore, be safely used only in the following situations: • The process has only one thread. • The process has multiple threads, but only one thread calls the heap functions for a specific heap. • The process has multiple threads, and the application provides its own mechanism for mutual exclusion to a specific heap. 15 LocalFree Function Frees the specified local memory object and invalidates its handle. Note The local functions have greater overhead and provide fewer features than other memory management functions. New applications should use the heap functions unless documentation states that a local function should be used. For more information, see Global and Local Functions. Syntax C++ HLOCAL WINAPI LocalFree( __in HLOCAL hMem ); Parameters hMem [in] A handle to the local memory object. This handle is returned by either the LocalAlloc or LocalReAlloc function. It is not safe to free memory allocated with GlobalAlloc. Return Value If the function succeeds, the return value is NULL. If the function fails, the return value is equal to a handle to the local memory object. To get extended error information, call GetLastError. Remarks If the process tries to examine or modify the memory after it has been freed, heap corruption may occur or an access violation exception (EXCEPTION_ACCESS_VIOLATION) may be generated. If the hMem parameter is NULL, LocalFree ignores the parameter and returns NULL.
  • 28. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 The LocalFree function will free a locked memory object. A locked memory object has a lock count greater than zero. The LocalLock function locks a local memory object and increments the lock count by one. The LocalUnlock function unlocks it and decrements the lock count by one. To get the lock count of a local memory object, use the LocalFlags function. If an application is running under a debug version of the system, LocalFree will issue a message that tells you that a locked object is being freed. If you are debugging the application, LocalFree will enter a breakpoint just before freeing a locked object. This allows you to verify the intended behavior, then continue execution. 16 GetLastError Function Retrieves the calling thread's last-error code value. The last-error code is maintained on a per-thread basis. Multiple threads do not overwrite each other's last-error code. Visual Basic: Applications should call err.LastDllError instead of GetLastError. 17.CreateProcess This function is used to run a new program. It creates a new process and its primary thread. The new process executes the specified executable file. Note The remote application interface (RAPI) version of this function is named CeCreateProcess (RAPI). BOOL CreateProcess( LPCWSTR pszImageName, LPCWSTR pszCmdLine, LPSECURITY_ATTRIBUTES psaProcess, LPSECURITY_ATTRIBUTES psaThread, BOOL fInheritHandles, DWORD fdwCreate, LPVOID pvEnvironment, LPWSTR pszCurDir, LPSTARTUPINFOW psiStartInfo, LPPROCESS_INFORMATION pProcInfo ); Parameters pszImageName [in] Pointer to a null-terminated string that specifies the module to execute.
  • 29. 北京四元教育 http://www.bj111.cn 010-8956040,13691026331 The string can specify the full path and filename of the module to execute or it can specify a partial path and filename. The lpszImageName parameter must be non-NULL and must include the module name. pszCmdLine [in, out] Pointer to a null-terminated string that specifies the command line to execute. The system adds a null character to the command line, trimming the string if necessary, to indicate which file was used. The lpszCmdLine parameter can be NULL. In that case, the function uses the string pointed to by lpszImageName as the command line. If lpszImageName and lpszCmdLine are non-NULL, * lpszImageName specifies the module to execute, and * lpszCmdLine specifies the command line. 18 GetSystemTimeAsFileTime Retrieves the current system date and time. The information is in Coordinated Universal Time (UTC) format. Syntax C++ void WINAPI GetSystemTimeAsFileTime( __out LPFILETIME lpSystemTimeAsFileTime ); Parameters lpSystemTimeAsFileTime [out] A pointer to a FILETIME structure to receive the current system date and time in UTC format. Return Value