Win32 support file for 91.515 assignments 1 and 2
The Following file contains documentation on the Win32 system calls and has been extended to include functions for creating threads and working with threads. The file then continues with the previous documentation needed to create processes, shared memory (via memory mapped file objects) and semaphores. The material should help with the Win32 implementation of the 91.515 first assignment. Threads can be waited on in NT as in POSIX, but the generic WaitForSingleObject() call (described towards the end of this file) is used with the thread handle of thread you want to wait for (there is no specific call like the pthread_join() call used in POSIX). Semaphore synchronization can be used in the thread version of the assignment just as we used it in the original process based version.
The CreateThread function creates a thread to execute within the address space of the calling process.
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES
lpThreadAttributes, // pointer to security attributes
DWORD dwStackSize, // initial thread stack size
LPTHREAD_START_ROUTINE lpStartAddress, // pointer to thread function
LPVOID lpParameter, // argument for new thread
DWORD dwCreationFlags, // creation flags
LPDWORD lpThreadId // pointer to receive thread ID
);
If the function succeeds, the return value is a handle to the new thread.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Windows 95 and Windows 98: CreateThread succeeds only when it is called in the context of a 32-bit program. A 32-bit DLL cannot create an additional thread when that DLL is being called by a 16-bit program.
The new thread handle is created with THREAD_ALL_ACCESS to the new thread. If a security descriptor is not provided, the handle can be used in any function that requires a thread object handle. When a security descriptor is provided, an access check is performed on all subsequent uses of the handle before access is granted. If the access check denies access, the requesting process cannot use the handle to gain access to the thread.
The thread execution begins at the function specified by the lpStartAddress parameter. If this function returns, the DWORD return value is used to terminate the thread in an implicit call to the ExitThread function. Use the GetExitCodeThread function to get the thread's return value.
The CreateThread function may succeed even if lpStartAddress points to data, code, or is not accessible. If the start address is invalid when the thread runs, an exception occurs, and the thread terminates. Thread termination due to a invalid start address is handled as an error exit for the thread's process. This behavior is similar to the asynchronous nature of CreateProcess, where the process is created even if it refers to invalid or missing dynamic-link libraries (DLLs).
The thread is created with a thread priority of THREAD_PRIORITY_NORMAL. Use the GetThreadPriority and SetThreadPriority functions to get and set the priority value of a thread.
When a thread terminates, the thread object attains a signaled state, satisfying any threads that were waiting on the object.
The thread object remains in the system until the thread has terminated and all handles to it have been closed through a call to CloseHandle.
The ExitProcess, ExitThread, CreateThread, CreateRemoteThread functions, and a process that is starting (as the result of a call by CreateProcess) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means that the following restrictions hold:
A thread that uses functions from the C run-time libraries should use the beginthread and endthread C run-time functions for thread management rather than CreateThread and ExitThread. Failure to do so results in small memory leaks when ExitThread is called.
Windows CE: The lpThreadAttributes parameter must be set to NULL. The dwStackSize parameter must be zero. Only zero or CREATE_SUSPENDED values are supported for the dwCreationFlags parameter.
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.01 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Processes and Threads Overview, Process and Thread Functions, CloseHandle, CreateProcess, CreateRemoteThread, ExitProcess, ExitThread, GetExitCodeThread, GetThreadPriority, ResumeThread, SetThreadPriority, SECURITY_ATTRIBUTES, ThreadProc
The ExitThread function ends a thread.
VOID ExitThread(
DWORD
dwExitCode // exit code for this thread
);
This function does not return a value.
ExitThread is the preferred method of exiting a thread. When this function is called (either explicitly or by returning from a thread procedure), the current thread's stack is deallocated and the thread terminates. The entry-point function of all attached dynamic-link libraries (DLLs) is invoked with a value indicating that the thread is detaching from the DLL.
If the thread is the last thread in the process when this function is called, the thread's process is also terminated.
The state of the thread object becomes signaled, releasing any other threads that had been waiting for the thread to terminate. The thread's termination status changes from STILL_ACTIVE to the value of the dwExitCode parameter.
Terminating a thread does not necessarily remove the thread object from the operating system. A thread object is deleted when the last handle to the thread is closed.
The ExitProcess, ExitThread, CreateThread, CreateRemoteThread functions, and a process that is starting (as the result of a CreateProcess call) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means the following restrictions hold:
A thread that uses functions from the C run-time libraries should use the _beginthread and _endthread C run-time functions for thread management rather than CreateThread and ExitThread. Failure to do so results in small memory leaks when ExitThread is called.
Windows CE: If the primary thread calls the ExitThread function, the application will exit.
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Processes and Threads Overview, Process and Thread Functions, CreateProcess, CreateRemoteThread, CreateThread, ExitProcess, FreeLibraryAndExitThread, GetExitCodeThread, TerminateThread
The GetCurrentThreadId function returns the thread identifier of the calling thread.
DWORD GetCurrentThreadId(VOID)
This function has no parameters.
The return value is the thread identifier of the calling thread.
Until the thread terminates, the thread identifier uniquely identifies the thread throughout the system.
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Processes and Threads Overview, Process and Thread Functions, GetCurrentThread
The CreateFile function creates or opens the following objects and returns a handle that can be used to access the object:
HANDLE CreateFile(
LPCTSTR
lpFileName, // pointer to name of the file
DWORD dwDesiredAccess, // access (read-write) mode
DWORD dwShareMode, // share mode
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
// pointer to security attributes
DWORD dwCreationDisposition, // how to create
DWORD dwFlagsAndAttributes, // file attributes
HANDLE hTemplateFile // handle to file with attributes to
// copy
);
|
Value |
Meaning |
|
0 |
Specifies device query access to the object. An application can query device attributes without accessing the device. |
|
GENERIC_READ |
Specifies read access to the object. Data can be read from the file and the file pointer can be moved. Combine with GENERIC_WRITE for read-write access. |
|
GENERIC_WRITE |
Specifies write access to the object. Data can be written to the file and the file pointer can be moved. Combine with GENERIC_READ for read-write access. |
|
Value |
Meaning |
|
FILE_SHARE_DELETE |
Windows NT: Subsequent open operations on the object will succeed only if delete access is requested. |
|
FILE_SHARE_READ |
Subsequent open operations on the object will succeed only if read access is requested. |
|
FILE_SHARE_WRITE |
Subsequent open operations on the object will succeed only if write access is requested. |
|
Value |
Meaning |
|
CREATE_NEW |
Creates a new file. The function fails if the specified file already exists. |
|
CREATE_ALWAYS |
Creates a new file. If the file exists, the function overwrites the file and clears the existing attributes. |
|
OPEN_EXISTING |
Opens the file. The function fails if the file does not exist. |
|
See the Remarks section for a discussion of why you should use the OPEN_EXISTING flag if you are using the CreateFile function for devices, including the console. |
|
|
OPEN_ALWAYS |
Opens the file, if it exists. If the file does not exist, the function creates the file as if dwCreationDisposition were CREATE_NEW. |
|
TRUNCATE_EXISTING |
Opens the file. Once opened, the file is truncated so that its size is zero bytes. The calling process must open the file with at least GENERIC_WRITE access. The function fails if the file does not exist. |
|
Attribute |
Meaning |
|
FILE_ATTRIBUTE_ARCHIVE |
The file should be archived. Applications use this attribute to mark files for backup or removal. |
|
FILE_ATTRIBUTE_HIDDEN |
The file is hidden. It is not to be included in an ordinary directory listing. |
|
FILE_ATTRIBUTE_NORMAL |
The file has no other attributes set. This attribute is valid only if used alone. |
|
FILE_ATTRIBUTE_OFFLINE |
The data of the file is not immediately available. Indicates that the file data has been physically moved to offline storage. |
|
FILE_ATTRIBUTE_READONLY |
The file is read only. Applications can read the file but cannot write to it or delete it. |
|
FILE_ATTRIBUTE_SYSTEM |
The file is part of or is used exclusively by the operating system. |
|
FILE_ATTRIBUTE_TEMPORARY |
The file is being used for temporary storage. File systems attempt to keep all of the data in memory for quicker access rather than flushing the data back to mass storage. A temporary file should be deleted by the application as soon as it is no longer needed. |
|
Flag |
Meaning |
|
FILE_FLAG_WRITE_THROUGH |
|
|
Instructs the system to write through any intermediate cache and go directly to disk. The system can still cache write operations, but cannot lazily flush them. |
|
|
FILE_FLAG_OVERLAPPED |
|
|
Instructs the system to initialize the object, so that operations that take a significant amount of time to process return ERROR_IO_PENDING. When the operation is finished, the specified event is set to the signaled state. |
|
|
When you specify FILE_FLAG_OVERLAPPED, the file read and write functions must specify an OVERLAPPED structure. That is, when FILE_FLAG_OVERLAPPED is specified, an application must perform overlapped reading and writing. |
|
|
When FILE_FLAG_OVERLAPPED is specified, the system does not maintain the file pointer. The file position must be passed as part of the lpOverlapped parameter (pointing to an OVERLAPPED structure) to the file read and write functions. |
|
|
This flag also enables more than one operation to be performed simultaneously with the handle (a simultaneous read and write operation, for example). |
|
|
FILE_FLAG_NO_BUFFERING |
|
|
Instructs the system to open the file with no intermediate buffering or caching. When combined with FILE_FLAG_OVERLAPPED, the flag gives maximum asynchronous performance, because the I/O does not rely on the synchronous operations of the memory manager. However, some I/O operations will take longer, because data is not being held in the cache. An application must meet certain requirements when working with files opened with FILE_FLAG_NO_BUFFERING:
One way to align buffers on integer multiples of the volume sector size is to use VirtualAlloc to allocate the buffers. It allocates memory that is aligned on addresses that are integer multiples of the operating system's memory page size. Because both memory page and volume sector sizes are powers of 2, this memory is also aligned on addresses that are integer multiples of a volume's sector size. An application can determine a volume's sector size by calling the GetDiskFreeSpace function. |
|
|
FILE_FLAG_RANDOM_ACCESS |
|
|
Indicates that the file is accessed randomly. The system can use this as a hint to optimize file caching. |
|
|
FILE_FLAG_SEQUENTIAL_SCAN |
|
|
Indicates that the file is to be accessed sequentially from beginning to end. The system can use this as a hint to optimize file caching. If an application moves the file pointer for random access, optimum caching may not occur; however, correct operation is still guaranteed. |
|
|
Specifying this flag can increase performance for applications that read large files using sequential access. Performance gains can be even more noticeable for applications that read large files mostly sequentially, but occasionally skip over small ranges of bytes. |
|
|
FILE_FLAG_DELETE_ON_CLOSE |
|
|
Indicates that the operating system is to delete the file immediately after all of its handles have been closed, not just the handle for which you specified FILE_FLAG_DELETE_ON_CLOSE. Subsequent open requests for the file will fail, unless FILE_SHARE_DELETE is used. |
|
|
FILE_FLAG_BACKUP_SEMANTICS |
|
|
Windows NT: Indicates that the file is being opened or created for a backup or restore operation. The system ensures that the calling process overrides file security checks, provided it has the necessary privileges. The relevant privileges are SE_BACKUP_NAME and SE_RESTORE_NAME. You can also set this flag to obtain a handle to a directory. A directory handle can be passed to some Win32 functions in place of a file handle. |
|
|
FILE_FLAG_POSIX_SEMANTICS |
|
|
Indicates that the file is to be accessed according to POSIX rules. This includes allowing multiple files with names, differing only in case, for file systems that support such naming. Use care when using this option because files created with this flag may not be accessible by applications written for MS-DOS or 16-bit Windows. |
|
|
FILE_FLAG_OPEN_REPARSE_POINT |
|
|
Specifying this flag inhibits the reparse behavior of NTFS reparse points. When the file is opened, a file handle is returned, whether the filter that controls the reparse point is operational or not. This flag cannot be used with the CREATE_ALWAYS flag. |
|
|
FILE_FLAG_OPEN_NO_RECALL |
|
|
Indicates that the file data is requested, but it should continue to reside in remote storage. It should not be transported back to local storage. This flag is intended for use by remote storage systems or the Hierarchical Storage Management system. |
|
|
Value |
Meaning |
|
SECURITY_ANONYMOUS |
Specifies to impersonate the client at the Anonymous impersonation level. |
|
SECURITY_IDENTIFICATION |
Specifies to impersonate the client at the Identification impersonation level. |
|
SECURITY_IMPERSONATION |
Specifies to impersonate the client at the Impersonation impersonation level. |
|
SECURITY_DELEGATION |
Specifies to impersonate the client at the Delegation impersonation level. |
|
SECURITY_CONTEXT_TRACKING |
Specifies that the security tracking mode is dynamic. If this flag is not specified, Security Tracking Mode is static. |
|
SECURITY_EFFECTIVE_ONLY |
Specifies that only the enabled aspects of the client's security context are available to the server. If you do not specify this flag, all aspects of the client's security context are available. This flag allows the client to limit the groups and privileges that a server can use while impersonating the client. |
If the function succeeds, the return value is an open handle to the specified file. If the specified file exists before the function call and dwCreationDisposition is CREATE_ALWAYS or OPEN_ALWAYS, a call to GetLastError returns ERROR_ALREADY_EXISTS (even though the function has succeeded). If the file does not exist before the call, GetLastError returns zero.
If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.
Use the CloseHandle function to close an object handle returned by CreateFile.
As noted above, specifying zero for dwDesiredAccess allows an application to query device attributes without actually accessing the device. This type of querying is useful, for example, if an application wants to determine the size of a floppy disk drive and the formats it supports without having a floppy in the drive.
When creating a new file, the CreateFile function performs the following actions:
When opening an existing file, CreateFile performs the following actions:
If you are attempting to create a file on a floppy drive that does not have a floppy disk or a CD-ROM drive that does not have a CD, the system displays a message box asking the user to insert a disk or a CD, respectively. To prevent the system from displaying this message box, call the SetErrorMode function with SEM_FAILCRITICALERRORS.
Windows NT: Some file systems, such as NTFS, support compression or encryption for individual files and directories. On volumes formatted for such a file system, a new file inherits the compression and encryption attributes of its directory.
You cannot use the CreateFile function to set a file's compression or encryption state. Use the DeviceIoControl function to set a file's compression state. Use the EncryptFile function to set a file's encryption state.
If CreateFile opens the client end of a named pipe, the function uses any instance of the named pipe that is in the listening state. The opening process can duplicate the handle as many times as required but, once opened, the named pipe instance cannot be opened by another client. The access specified when a pipe is opened must be compatible with the access specified in the dwOpenMode parameter of the CreateNamedPipe function. For more information about pipes, see Pipes.
If CreateFile opens the client end of a mailslot, the function returns INVALID_HANDLE_VALUE if the mailslot client attempts to open a local mailslot before the mailslot server has created it with the CreateMailSlot function. For more information about mailslots, see Mailslots.
The CreateFile function can create a handle to a communications resource, such as the serial port COM1. For communications resources, the dwCreationDisposition parameter must be OPEN_EXISTING, and the hTemplate parameter must be NULL. Read, write, or read-write access can be specified, and the handle can be opened for overlapped I/O. For more information about communications, see Communications.
Disk Devices
Windows NT: You can use the CreateFile function to open a disk drive or a partition on a disk drive. The function returns a handle to the disk device; that handle can be used with the DeviceIOControl function. The following requirements must be met in order for such a call to succeed:
|
String |
Meaning |
|
\\.\PHYSICALDRIVE2 |
Obtains a handle to the third physical drive on the user's computer. |
|
String |
Meaning |
|
\\.\A: |
Obtains a handle to drive A on the user's computer. |
|
\\.\C: |
Obtains a handle to drive C on the user's computer. |
Note that all I/O buffers must be sector aligned (aligned on addresses in memory that are integer multiples of the volume's sector size), even if the disk device is opened without the FILE_FLAG_NO_BUFFERING flag.
Windows 95: This technique does not work for opening a logical drive. In Windows 95, specifying a string in this form causes CreateFile to return an error.
The CreateFile function can create a handle to console input (CONIN$). If the process has an open handle to it as a result of inheritance or duplication, it can also create a handle to the active screen buffer (CONOUT$). The calling process must be attached to an inherited console or one allocated by the AllocConsole function. For console handles, set the CreateFile parameters as follows:
|
Parameters |
Value |
|
lpFileName |
Use the CONIN$ value to specify console input and the CONOUT$ value to specify console output. |
|
CONIN$ gets a handle to the console's input buffer, even if the SetStdHandle function redirected the standard input handle. To get the standard input handle, use the GetStdHandle function. |
|
|
CONOUT$ gets a handle to the active screen buffer, even if SetStdHandle redirected the standard output handle. To get the standard output handle, use GetStdHandle. |
|
|
dwDesiredAccess |
GENERIC_READ | GENERIC_WRITE is preferred, but either one can limit access. |
|
dwShareMode |
If the calling process inherited the console or if a child process should be able to access the console, this parameter must be FILE_SHARE_READ | FILE_SHARE_WRITE. |
|
lpSecurityAttributes |
If you want the console to be inherited, the bInheritHandle member of the SECURITY_ATTRIBUTES structure must be TRUE. |
|
dwCreationDisposition |
You should specify OPEN_EXISTING when using CreateFile to open the console. |
|
dwFlagsAndAttributes |
Ignored. |
|
hTemplateFile |
Ignored. |
The following list shows the effects of various settings of fwdAccess and lpFileName.
|
lpFileName |
fwdAccess |
Result |
|
CON |
GENERIC_READ |
Opens console for input. |
|
CON |
GENERIC_WRITE |
Opens console for output. |
|
CON |
GENERIC_READ\ |
Windows 95: Causes CreateFile to fail; GetLastError returns ERROR_PATH_NOT_FOUND. Windows NT: Causes CreateFile to fail; GetLastError returns ERROR_FILE_NOT_FOUND. |
An application cannot create a directory with CreateFile; it must call CreateDirectory or CreateDirectoryEx to create a directory.
Windows NT: You can obtain a handle to a directory by setting the FILE_FLAG_BACKUP_SEMANTICS flag. A directory handle can be passed to some Win32 functions in place of a file handle.
Some file systems, such as NTFS, support compression or encryption for individual files and directories. On volumes formatted for such a file system, a new directory inherits the compression and encryption attributes of its parent directory.
You cannot use the CreateFile function to set a directory's compression or encryption state. Use the DeviceIoControl function to set a directory's compression state. Use the EncryptFile function to set a directory's encryption state.
Windows CE: Windows CE uses special device file names to access peripheral devices. For information on the format of these names, see the Windows CE Device Driver Kit documentation.
The lpSecurityAttributes parameter is ignored and should be set to NULL.
The following attribute flags are not supported for the dwFlagsAndAttributes parameter:
FILE_ATTRIBUTE_OFFLINE
FILE_ATTRIBUTE_TEMPORARY
The following file flags are not supported for the dwFlagsAndAttributes parameter:
FILE_FLAG_OVERLAPPED However, multiple reads/writes pending on a device at a time are allowed.
FILE_FLAG_SEQUENTIAL_SCAN
FILE_FLAG_NO_BUFFERING
FILE_FLAG_DELETE_ON_CLOSE
FILE_FLAG_BACKUP_SEMANTICS
FILE_FLAG_POSIX_SEMANTICS
The dwFlagsAndAttributes parameter does not support the SECURITY_SQOS_PRESENT flag or its corresponding values.
The hTemplateFile parameter is ignored and as a result CreateFile does not copy the extended attributes to the new file.
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.
File I/O Overview, File Functions, AllocConsole, CloseHandle, ConnectNamedPipe, CreateDirectory, CreateDirectoryEx, CreateNamedPipe, DeviceIOControl, GetDiskFreeSpace, GetOverlappedResult, GetStdHandle, OpenFile, OVERLAPPED, ReadFile, SECURITY_ATTRIBUTES, SetErrorMode, SetStdHandle TransactNamedPipe, VirtualAlloc, WriteFile
The CreateFile function creates or opens the following objects and returns a handle that can be used to access the object:
HANDLE CreateFile(
LPCTSTR
lpFileName, // pointer to name of the file
DWORD dwDesiredAccess, // access (read-write) mode
DWORD dwShareMode, // share mode
LPSECURITY_ATTRIBUTES lpSecurityAttributes,
// pointer to security attributes
DWORD dwCreationDisposition, // how to create
DWORD dwFlagsAndAttributes, // file attributes
HANDLE hTemplateFile // handle to file with attributes to
// copy
);
|
Value |
Meaning |
|
0 |
Specifies device query access to the object. An application can query device attributes without accessing the device. |
|
GENERIC_READ |
Specifies read access to the object. Data can be read from the file and the file pointer can be moved. Combine with GENERIC_WRITE for read-write access. |
|
GENERIC_WRITE |
Specifies write access to the object. Data can be written to the file and the file pointer can be moved. Combine with GENERIC_READ for read-write access. |
|
Value |
Meaning |
|
FILE_SHARE_DELETE |
Windows NT: Subsequent open operations on the object will succeed only if delete access is requested. |
|
FILE_SHARE_READ |
Subsequent open operations on the object will succeed only if read access is requested. |
|
FILE_SHARE_WRITE |
Subsequent open operations on the object will succeed only if write access is requested. |
|
Value |
Meaning |
|
CREATE_NEW |
Creates a new file. The function fails if the specified file already exists. |
|
CREATE_ALWAYS |
Creates a new file. If the file exists, the function overwrites the file and clears the existing attributes. |
|
OPEN_EXISTING |
Opens the file. The function fails if the file does not exist. |
|
See the Remarks section for a discussion of why you should use the OPEN_EXISTING flag if you are using the CreateFile function for devices, including the console. |
|
|
OPEN_ALWAYS |
Opens the file, if it exists. If the file does not exist, the function creates the file as if dwCreationDisposition were CREATE_NEW. |
|
TRUNCATE_EXISTING |
Opens the file. Once opened, the file is truncated so that its size is zero bytes. The calling process must open the file with at least GENERIC_WRITE access. The function fails if the file does not exist. |
|
Attribute |
Meaning |
|
FILE_ATTRIBUTE_ARCHIVE |
The file should be archived. Applications use this attribute to mark files for backup or removal. |
|
FILE_ATTRIBUTE_HIDDEN |
The file is hidden. It is not to be included in an ordinary directory listing. |
|
FILE_ATTRIBUTE_NORMAL |
The file has no other attributes set. This attribute is valid only if used alone. |
|
FILE_ATTRIBUTE_OFFLINE |
The data of the file is not immediately available. Indicates that the file data has been physically moved to offline storage. |
|
FILE_ATTRIBUTE_READONLY |
The file is read only. Applications can read the file but cannot write to it or delete it. |
|
FILE_ATTRIBUTE_SYSTEM |
The file is part of or is used exclusively by the operating system. |
|
FILE_ATTRIBUTE_TEMPORARY |
The file is being used for temporary storage. File systems attempt to keep all of the data in memory for quicker access rather than flushing the data back to mass storage. A temporary file should be deleted by the application as soon as it is no longer needed. |
|
FlagMeaning |
|
|
FILE_FLAG_WRITE_THROUGH |
|
|
Instructs the system to write through any intermediate cache and go directly to disk. The system can still cache write operations, but cannot lazily flush them. |
|
|
FILE_FLAG_OVERLAPPED |
|
|
Instructs the system to initialize the object, so that operations that take a significant amount of time to process return ERROR_IO_PENDING. When the operation is finished, the specified event is set to the signaled state. |
|
|
When you specify FILE_FLAG_OVERLAPPED, the file read and write functions must specify an OVERLAPPED structure. That is, when FILE_FLAG_OVERLAPPED is specified, an application must perform overlapped reading and writing. |
|
|
When FILE_FLAG_OVERLAPPED is specified, the system does not maintain the file pointer. The file position must be passed as part of the lpOverlapped parameter (pointing to an OVERLAPPED structure) to the file read and write functions. |
|
|
This flag also enables more than one operation to be performed simultaneously with the handle (a simultaneous read and write operation, for example). |
|
|
FILE_FLAG_NO_BUFFERING |
|
|
Instructs the system to open the file with no intermediate buffering or caching. When combined with FILE_FLAG_OVERLAPPED, the flag gives maximum asynchronous performance, because the I/O does not rely on the synchronous operations of the memory manager. However, some I/O operations will take longer, because data is not being held in the cache. An application must meet certain requirements when working with files opened with FILE_FLAG_NO_BUFFERING:
One way to align buffers on integer multiples of the volume sector size is to use VirtualAlloc to allocate the buffers. It allocates memory that is aligned on addresses that are integer multiples of the operating system's memory page size. Because both memory page and volume sector sizes are powers of 2, this memory is also aligned on addresses that are integer multiples of a volume's sector size. An application can determine a volume's sector size by calling the GetDiskFreeSpace function. |
|
|
FILE_FLAG_RANDOM_ACCESS |
|
|
Indicates that the file is accessed randomly. The system can use this as a hint to optimize file caching. |
|
|
FILE_FLAG_SEQUENTIAL_SCAN |
|
|
Indicates that the file is to be accessed sequentially from beginning to end. The system can use this as a hint to optimize file caching. If an application moves the file pointer for random access, optimum caching may not occur; however, correct operation is still guaranteed. |
|
|
Specifying this flag can increase performance for applications that read large files using sequential access. Performance gains can be even more noticeable for applications that read large files mostly sequentially, but occasionally skip over small ranges of bytes. |
|
|
FILE_FLAG_DELETE_ON_CLOSE |
|
|
Indicates that the operating system is to delete the file immediately after all of its handles have been closed, not just the handle for which you specified FILE_FLAG_DELETE_ON_CLOSE. Subsequent open requests for the file will fail, unless FILE_SHARE_DELETE is used. |
|
|
FILE_FLAG_BACKUP_SEMANTICS |
|
|
Windows NT: Indicates that the file is being opened or created for a backup or restore operation. The system ensures that the calling process overrides file security checks, provided it has the necessary privileges. The relevant privileges are SE_BACKUP_NAME and SE_RESTORE_NAME. You can also set this flag to obtain a handle to a directory. A directory handle can be passed to some Win32 functions in place of a file handle. |
|
|
FILE_FLAG_POSIX_SEMANTICS |
|
|
Indicates that the file is to be accessed according to POSIX rules. This includes allowing multiple files with names, differing only in case, for file systems that support such naming. Use care when using this option because files created with this flag may not be accessible by applications written for MS-DOS or 16-bit Windows. |
|
|
FILE_FLAG_OPEN_REPARSE_POINT |
|
|
Specifying this flag inhibits the reparse behavior of NTFS reparse points. When the file is opened, a file handle is returned, whether the filter that controls the reparse point is operational or not. This flag cannot be used with the CREATE_ALWAYS flag. |
|
|
FILE_FLAG_OPEN_NO_RECALL |
|
|
Indicates that the file data is requested, but it should continue to reside in remote storage. It should not be transported back to local storage. This flag is intended for use by remote storage systems or the Hierarchical Storage Management system. |
|
|
Value |
Meaning |
|
SECURITY_ANONYMOUS |
Specifies to impersonate the client at the Anonymous impersonation level. |
|
SECURITY_IDENTIFICATION |
Specifies to impersonate the client at the Identification impersonation level. |
|
SECURITY_IMPERSONATION |
Specifies to impersonate the client at the Impersonation impersonation level. |
|
SECURITY_DELEGATION |
Specifies to impersonate the client at the Delegation impersonation level. |
|
SECURITY_CONTEXT_TRACKING |
Specifies that the security tracking mode is dynamic. If this flag is not specified, Security Tracking Mode is static. |
|
SECURITY_EFFECTIVE_ONLY |
Specifies that only the enabled aspects of the client's security context are available to the server. If you do not specify this flag, all aspects of the client's security context are available. This flag allows the client to limit the groups and privileges that a server can use while impersonating the client. |
If the function succeeds, the return value is an open handle to the specified file. If the specified file exists before the function call and dwCreationDisposition is CREATE_ALWAYS or OPEN_ALWAYS, a call to GetLastError returns ERROR_ALREADY_EXISTS (even though the function has succeeded). If the file does not exist before the call, GetLastError returns zero.
If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.
Use the CloseHandle function to close an object handle returned by CreateFile.
As noted above, specifying zero for dwDesiredAccess allows an application to query device attributes without actually accessing the device. This type of querying is useful, for example, if an application wants to determine the size of a floppy disk drive and the formats it supports without having a floppy in the drive.
When creating a new file, the CreateFile function performs the following actions:
When opening an existing file, CreateFile performs the following actions:
If you are attempting to create a file on a floppy drive that does not have a floppy disk or a CD-ROM drive that does not have a CD, the system displays a message box asking the user to insert a disk or a CD, respectively. To prevent the system from displaying this message box, call the SetErrorMode function with SEM_FAILCRITICALERRORS.
Windows NT: Some file systems, such as NTFS, support compression or encryption for individual files and directories. On volumes formatted for such a file system, a new file inherits the compression and encryption attributes of its directory.
You cannot use the CreateFile function to set a file's compression or encryption state. Use the DeviceIoControl function to set a file's compression state. Use the EncryptFile function to set a file's encryption state.
If CreateFile opens the client end of a named pipe, the function uses any instance of the named pipe that is in the listening state. The opening process can duplicate the handle as many times as required but, once opened, the named pipe instance cannot be opened by another client. The access specified when a pipe is opened must be compatible with the access specified in the dwOpenMode parameter of the CreateNamedPipe function. For more information about pipes, see Pipes.
If CreateFile opens the client end of a mailslot, the function returns INVALID_HANDLE_VALUE if the mailslot client attempts to open a local mailslot before the mailslot server has created it with the CreateMailSlot function. For more information about mailslots, see Mailslots.
The CreateFile function can create a handle to a communications resource, such as the serial port COM1. For communications resources, the dwCreationDisposition parameter must be OPEN_EXISTING, and the hTemplate parameter must be NULL. Read, write, or read-write access can be specified, and the handle can be opened for overlapped I/O. For more information about communications, see Communications.
Disk Devices
Windows NT: You can use the CreateFile function to open a disk drive or a partition on a disk drive. The function returns a handle to the disk device; that handle can be used with the DeviceIOControl function. The following requirements must be met in order for such a call to succeed:
|
String |
Meaning |
|
\\.\PHYSICALDRIVE2 |
Obtains a handle to the third physical drive on the user's computer. |
|
String |
Meaning |
|
\\.\A: |
Obtains a handle to drive A on the user's computer. |
|
\\.\C: |
Obtains a handle to drive C on the user's computer. |
Note that all I/O buffers must be sector aligned (aligned on addresses in memory that are integer multiples of the volume's sector size), even if the disk device is opened without the FILE_FLAG_NO_BUFFERING flag.
Windows 95: This technique does not work for opening a logical drive. In Windows 95, specifying a string in this form causes CreateFile to return an error.
The CreateFile function can create a handle to console input (CONIN$). If the process has an open handle to it as a result of inheritance or duplication, it can also create a handle to the active screen buffer (CONOUT$). The calling process must be attached to an inherited console or one allocated by the AllocConsole function. For console handles, set the CreateFile parameters as follows:
|
Parameters |
Value |
|
lpFileName |
Use the CONIN$ value to specify console input and the CONOUT$ value to specify console output. |
|
CONIN$ gets a handle to the console's input buffer, even if the SetStdHandle function redirected the standard input handle. To get the standard input handle, use the GetStdHandle function. |
|
|
CONOUT$ gets a handle to the active screen buffer, even if SetStdHandle redirected the standard output handle. To get the standard output handle, use GetStdHandle. |
|
|
dwDesiredAccess |
GENERIC_READ | GENERIC_WRITE is preferred, but either one can limit access. |
|
dwShareMode |
If the calling process inherited the console or if a child process should be able to access the console, this parameter must be FILE_SHARE_READ | FILE_SHARE_WRITE. |
|
lpSecurityAttributes |
If you want the console to be inherited, the bInheritHandle member of the SECURITY_ATTRIBUTES structure must be TRUE. |
|
dwCreationDisposition |
You should specify OPEN_EXISTING when using CreateFile to open the console. |
|
dwFlagsAndAttributes |
Ignored. |
|
hTemplateFile |
Ignored. |
The following list shows the effects of various settings of fwdAccess and lpFileName.
|
lpFileName |
fwdAccess |
Result |
|
CON |
GENERIC_READ |
Opens console for input. |
|
CON |
GENERIC_WRITE |
Opens console for output. |
|
CON |
GENERIC_READ\ |
Windows 95: Causes CreateFile to fail; GetLastError returns ERROR_PATH_NOT_FOUND. Windows NT: Causes CreateFile to fail; GetLastError returns ERROR_FILE_NOT_FOUND. |
An application cannot create a directory with CreateFile; it must call CreateDirectory or CreateDirectoryEx to create a directory.
Windows NT: You can obtain a handle to a directory by setting the FILE_FLAG_BACKUP_SEMANTICS flag. A directory handle can be passed to some Win32 functions in place of a file handle.
Some file systems, such as NTFS, support compression or encryption for individual files and directories. On volumes formatted for such a file system, a new directory inherits the compression and encryption attributes of its parent directory.
You cannot use the CreateFile function to set a directory's compression or encryption state. Use the DeviceIoControl function to set a directory's compression state. Use the EncryptFile function to set a directory's encryption state.
Windows CE: Windows CE uses special device file names to access peripheral devices. For information on the format of these names, see the Windows CE Device Driver Kit documentation.
The lpSecurityAttributes parameter is ignored and should be set to NULL.
The following attribute flags are not supported for the dwFlagsAndAttributes parameter:
FILE_ATTRIBUTE_OFFLINE
FILE_ATTRIBUTE_TEMPORARY
The following file flags are not supported for the dwFlagsAndAttributes parameter:
FILE_FLAG_OVERLAPPED However, multiple reads/writes pending on a device at a time are allowed.
FILE_FLAG_SEQUENTIAL_SCAN
FILE_FLAG_NO_BUFFERING
FILE_FLAG_DELETE_ON_CLOSE
FILE_FLAG_BACKUP_SEMANTICS
FILE_FLAG_POSIX_SEMANTICS
The dwFlagsAndAttributes parameter does not support the SECURITY_SQOS_PRESENT flag or its corresponding values.
The hTemplateFile parameter is ignored and as a result CreateFile does not copy the extended attributes to the new file.
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.
File I/O Overview, File Functions, AllocConsole, CloseHandle, ConnectNamedPipe, CreateDirectory, CreateDirectoryEx, CreateNamedPipe, DeviceIOControl, GetDiskFreeSpace, GetOverlappedResult, GetStdHandle, OpenFile, OVERLAPPED, ReadFile, SECURITY_ATTRIBUTES, SetErrorMode, SetStdHandle TransactNamedPipe, VirtualAlloc, WriteFile
The OpenFileMapping function opens a named file-mapping object.
HANDLE OpenFileMapping(
DWORD
dwDesiredAccess, // access mode
BOOL bInheritHandle, // inherit flag
LPCTSTR lpName // pointer to name of file-mapping object
);
|
Value |
Meaning |
|
FILE_MAP_WRITE |
Read-write access. The target file-mapping object must have been created with PAGE_READWRITE protection. A read-write view of the file is mapped. |
|
FILE_MAP_READ |
Read-only access. The target file-mapping object must have been created with PAGE_READWRITE or PAGE_READ protection. A read-only view of the file is mapped. |
|
FILE_MAP_ALL_ACCESS |
Same as FILE_MAP_WRITE. |
|
FILE_MAP_COPY |
Copy-on-write access. The target file-mapping object must have been created with PAGE_WRITECOPY protection. A copy-on-write view of the file is mapped. |
If the function succeeds, the return value is an open handle to the specified file-mapping object.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
The handle that OpenFileMapping returns can be used with any function that requires a handle to a file-mapping object.
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.
File Mapping Overview, File Mapping Functions, CreateFileMapping
The MapViewOfFile function maps a view of a file into the address space of the calling process.
LPVOID MapViewOfFile(
HANDLE
hFileMappingObject, // file-mapping object to map into
// address space
DWORD dwDesiredAccess, // access mode
DWORD dwFileOffsetHigh, // high-order 32 bits of file offset
DWORD dwFileOffsetLow, // low-order 32 bits of file offset
DWORD dwNumberOfBytesToMap // number of bytes to map
);
|
Value |
Meaning |
|
FILE_MAP_WRITE |
Read-write access. The hFileMappingObject parameter must have been created with PAGE_READWRITE protection. A read-write view of the file is mapped. |
|
FILE_MAP_READ |
Read-only access. The hFileMappingObject parameter must have been created with PAGE_READWRITE or PAGE_READONLY protection. A read-only view of the file is mapped. |
|
FILE_MAP_ALL_ACCESS |
Same as FILE_MAP_WRITE. |
|
FILE_MAP_COPY |
Copy on write access. If you create the map with PAGE_WRITECOPY and the view with FILE_MAP_COPY, you will receive a view to file. If you write to it, the pages are automatically swappable and the modifications you make will not go to the original data file. Windows 95: You must pass PAGE_WRITECOPY to CreateFileMapping; otherwise, an error will be returned. If you share the mapping between multiple processes using DuplicateHandle or OpenFileMapping and one process writes to a view, the modification is propagated to the other process. The original file does not change. Windows NT: There is no restriction as to how the hFileMappingObject parameter must be created. Copy on write is valid for any type of view. If you share the mapping between multiple processes using DuplicateHandle or OpenFileMapping and one process writes to a view, the modification is not propagated to the other process. The original file does not change. |
If the function succeeds, the return value is the starting address of the mapped view.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.
Mapping a file makes the specified portion of the file visible in the address space of the calling process.
Multiple views of a file (or a file-mapping object and its mapped file) are said to be "coherent" if they contain identical data at a specified time. This occurs if the file views are derived from the same file-mapping object. A process can duplicate a file-mapping object handle into another process by using the DuplicateHandle function, or another process can open a file-mapping object by name by using the OpenFileMapping function.
A mapped view of a file is not guaranteed to be coherent with a file being accessed by the ReadFile or WriteFile function.
Windows 95: MapViewOfFile may require the swapfile to grow. If the swapfile cannot grow, the function fails.
Windows NT: If the file-mapping object is backed by the paging file (handle = 0xFFFFFFFF), the paging file must be large enough to hold the entire mapping. If it is not, MapViewOfFile fails.
Note To guard against an access violation, use structured exception handling to protect any code that writes to or reads from a memory mapped view. For more information, see Reading and Writing.
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
File Mapping Overview, File Mapping Functions, CreateFileMapping, DuplicateHandle, GetSystemInfo, MapViewOfFileEx, MapViewOfFileVlm, OpenFileMapping, UnmapViewOfFile, UnmapViewOfFileVlm, SYSTEM_INFO
The UnmapViewOfFile function unmaps a mapped view of a file from the calling process's address space.
BOOL UnmapViewOfFile(
LPCVOID
lpBaseAddress // address where mapped view begins
);
If the function succeeds, the return value is nonzero, and all dirty pages within the specified range are written "lazily" to disk.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
Although an application may close the file handle used to create a file mapping object, the system holds the corresponding file open until the last view of the file is unmapped.
Windows 95: Files for which the last view has not yet been unmapped are held open with the same sharing restrictions as the original file handle.
Windows NT: Files for which the last view has not yet been unmapped are held open with no sharing restrictions.
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
File Mapping Overview, File Mapping Functions, MapViewOfFile, MapViewOfFileEx, UnmapViewOfFileVlm
The CreateSemaphore function creates a named or unnamed semaphore object.
HANDLE CreateSemaphore(
LPSECURITY_ATTRIBUTES
lpSemaphoreAttributes,
// pointer to security attributes
LONG lInitialCount, // initial count
LONG lMaximumCount, // maximum count
LPCTSTR lpName // pointer to semaphore-object name
);
If the function succeeds, the return value is a handle to the semaphore object. If the named semaphore 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.
The handle returned by CreateSemaphore has SEMAPHORE_ALL_ACCESS access to the new semaphore object and can be used in any function that requires a handle to a semaphore object.
Any thread of the calling process can specify the semaphore-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 state of a semaphore object is signaled when its count is greater than zero, and nonsignaled when its count is equal to zero. The lInitialCount parameter specifies the initial count. Each time a waiting thread is released because of the semaphore's signaled state, the count of the semaphore is decreased by one. Use the ReleaseSemaphore function to increment a semaphore's count by a specified amount. The count can never be less than zero or greater than the value specified in the lMaximumCount parameter.
Multiple processes can have handles of the same semaphore object, enabling use of the object for interprocess synchronization. The following object-sharing mechanisms are available:
Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The semaphore object is destroyed when its last handle has been closed.
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.
Synchronization Overview, Synchronization Functions, CloseHandle, CreateProcess, DuplicateHandle, OpenSemaphore, ReleaseSemaphore, SECURITY_ATTRIBUTES
The ReleaseSemaphore function increases the count of the specified semaphore object by a specified amount.
BOOL ReleaseSemaphore(
HANDLE
hSemaphore, // handle to the semaphore object
LONG lReleaseCount, // amount to add to current count
LPLONG lpPreviousCount // address of previous count
);
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.
The state of a semaphore object is signaled when its count is greater than zero and nonsignaled when its count is equal to zero. The process that calls the CreateSemaphore function specifies the semaphore's initial count. Each time a waiting thread is released because of the semaphore's signaled state, the count of the semaphore is decreased by one.
Typically, an application uses a semaphore to limit the number of threads using a resource. Before a thread uses the resource, it specifies the semaphore handle in a call to one of the wait functions. When the wait function returns, it decreases the semaphore's count by one. When the thread has finished using the resource, it calls ReleaseSemaphore to increase the semaphore's count by one.
Another use of ReleaseSemaphore is during an application's initialization. The application can create a semaphore with an initial count of zero. This sets the semaphore's state to nonsignaled and blocks all threads from accessing the protected resource. When the application finishes its initialization, it uses ReleaseSemaphore to increase the count to its maximum value, to permit normal access to the protected resource.
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Unsupported.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Synchronization Overview, Synchronization Functions, CreateSemaphore, OpenSemaphore
The WaitForSingleObject function returns when one of the following occurs:
DWORD WaitForSingleObject(
HANDLE
hHandle, // handle to object to wait for
DWORD dwMilliseconds // time-out interval in milliseconds
);
If the function succeeds, the return value indicates the event that caused the function to return. This value can be one of the following.
|
Value |
Meaning |
|
WAIT_ABANDONED |
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 is set to nonsignaled. |
|
WAIT_OBJECT_0 |
The state of the specified object is signaled. |
|
WAIT_TIMEOUT |
The time-out interval elapsed, and the object's state is nonsignaled. |
If the function fails, the return value is WAIT_FAILED. To get extended error information, call GetLastError.
The WaitForSingleObject function checks the current state of the specified object. If the object's state is nonsignaled, the calling thread enters an efficient wait state. The thread consumes very little processor time while waiting for the object state to become signaled or the time-out interval to elapse.
Before returning, a wait 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.
The WaitForSingleObject function can wait for the following objects:
For more information, see Synchronization Objects.
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 COM CoInitialize. Therefore, if you have a thread that creates windows, use MsgWaitForMultipleObjects or MsgWaitForMultipleObjectsEx, rather than WaitForSingleObject.
Windows CE: Windows CE does not support waiting for semaphores, change notification objects, console input, and timers.
Waiting on an invalid handle causes WaitForSingleObject to return WAIT_FAILED.
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Synchronization Overview, Synchronization Functions, CancelWaitableTimer, CreateEvent, CreateFile, CreateMutex, CreateProcess, CreateRemoteThread, CreateSemaphore, CreateThread, CreateWaitableTimer, FindFirstChangeNotification, GetStdHandle, MsgWaitForMultipleObjects, MsgWaitForMultipleObjectsEx, OpenEvent, OpenMutex, OpenProcess, OpenSemaphore, OpenWaitableTimer, PulseEvent, ResetEvent, SetEvent, SetWaitableTimer
The CreateProcess function creates a new process and its primary thread. The new process executes the specified executable file.
BOOL CreateProcess(
LPCTSTR
lpApplicationName,
// pointer to name of executable module
LPTSTR lpCommandLine, // pointer to command line string
LPSECURITY_ATTRIBUTES lpProcessAttributes, // process security attributes
LPSECURITY_ATTRIBUTES lpThreadAttributes, // thread security attributes
BOOL bInheritHandles, // handle inheritance flag
DWORD dwCreationFlags, // creation flags
LPVOID lpEnvironment, // pointer to new environment block
LPCTSTR lpCurrentDirectory, // pointer to current directory name
LPSTARTUPINFO lpStartupInfo, // pointer to STARTUPINFO
LPPROCESS_INFORMATION lpProcessInformation // pointer to PROCESS_INFORMATION
);
|
Value |
Meaning |
|
CREATE_DEFAULT_ERROR_MODE |
|
|
The new process does not inherit the error mode of the calling process. Instead, CreateProcess gives the new process the current default error mode. An application sets the current default error mode by calling SetErrorMode. This flag is particularly useful for multi-threaded shell applications that run with hard errors disabled. The default behavior for CreateProcess is for the new process to inherit the error mode of the caller. Setting this flag changes that default behavior. |
|
|
CREATE_NEW_CONSOLE |
|
|
The new process has a new console, instead of inheriting the parent's console. This flag cannot be used with the DETACHED_PROCESS flag. |
|
|
CREATE_NEW_PROCESS_GROUP |
|
|
The new process is the root process of a new process group. The process group includes all processes that are descendants of this root process. The process identifier of the new process group is the same as the process identifier, which is returned in the lpProcessInformation parameter. Process groups are used by the GenerateConsoleCtrlEvent function to enable sending a ctrl+c or ctrl+break signal to a group of console processes. |
|
|
CREATE_SEPARATE_WOW_VDM |
|
|
Windows NT: This flag is valid only when starting a 16-bit Windows-based application. If set, the new process is run in a private Virtual DOS Machine (VDM). By default, all 16-bit Windows-based applications are run as threads in a single, shared VDM. The advantage of running separately is that a crash only kills the single VDM; any other programs running in distinct VDMs continue to function normally. Also, 16-bit Windows-based applications that are run in separate VDMs have separate input queues. That means that if one application hangs momentarily, applications in separate VDMs continue to receive input. The disadvantage of running separately is that it takes significantly more memory to do so. You should use this flag only if the user requests that 16-bit applications should run in them own VDM. |
|
|
CREATE_SHARED_WOW_VDM |
|
|
Windows NT: The flag is valid only when starting a 16-bit Windows-based application. If the DefaultSeparateVDM switch in the Windows section of WIN.INI is TRUE, this flag causes the CreateProcess function to override the switch and run the new process in the shared Virtual DOS Machine. |
|
|
CREATE_SUSPENDED |
|
|
The primary thread of the new process is created in a suspended state, and does not run until the ResumeThread function is called. |
|
|
CREATE_UNICODE_ENVIRONMENT |
|
|
If set, the environment block pointed to by lpEnvironment uses Unicode characters. If clear, the environment block uses ANSI characters. |
|
|
DEBUG_PROCESS |
|
|
If this flag is set, the calling process is treated as a debugger, and the new process is a process being debugged. The system notifies the debugger of all debug events that occur in the process being debugged. If you create a process with this flag set, only the calling thread (the thread that called CreateProcess) can call the WaitForDebugEvent function. Windows 95 and Windows 98: This flag is not valid if the new process is a 16-bit application. |
|
|
DEBUG_ONLY_THIS_PROCESS |
|
|
If not set and the calling process is being debugged, the new process becomes another process being debugged by the calling process's debugger. If the calling process is not a process being debugged, no debugging-related actions occur. |
|
|
DETACHED_PROCESS |
|
|
For console processes, the new process does not have access to the console of the parent process. The new process can call the AllocConsole function at a later time to create a new console. This flag cannot be used with the CREATE_NEW_CONSOLE flag. |
|
|
Priority |
Meaning |
|
HIGH_PRIORITY_CLASS |
Indicates a process that performs time-critical tasks that must be executed immediately for it to run correctly. The threads of a high-priority class process preempt the threads of normal-priority or idle-priority class processes. An example is the Task List, which must respond quickly when called by the user, regardless of the load on the system. Use extreme care when using the high-priority class, because a high-priority class CPU-bound application can use nearly all available cycles. |
|
IDLE_PRIORITY_CLASS |
Indicates a process whose threads run only when the system is idle and are preempted by the threads of any process running in a higher priority class. An example is a screen saver. The idle priority class is inherited by child processes. |
|
NORMAL_PRIORITY_CLASS |
Indicates a normal process with no special scheduling needs. |
|
REALTIME_PRIORITY_CLASS |
Indicates a process that has the highest possible priority. The threads of a real-time priority class process preempt the threads of all other processes, including operating system processes performing important tasks. For example, a real-time process that executes for more than a very brief interval can cause disk caches not to flush or cause the mouse to be unresponsive. |
name=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.
The CreateProcess function is used to run a new program. The WinExec and LoadModule functions are still available, but they are implemented as calls to CreateProcess.
In addition to creating a process, CreateProcess also creates a thread object. The thread is created with an initial stack whose size is described in the image header of the specified program's executable file. The thread begins execution at the image's entry point.
The new process and the new thread handles are created with full access rights. For either handle, if a security descriptor is not provided, the handle can be used in any function that requires an object handle to that type. When a security descriptor is provided, an access check is performed on all subsequent uses of the handle before access is granted. If the access check denies access, the requesting process is not able to use the handle to gain access to the thread.
The process is assigned a 32-bit process identifier. The identifier is valid until the process terminates. It can be used to identify the process, or specified in the OpenProcess function to open a handle to the process. The initial thread in the process is also assigned a 32-bit thread identifier. The identifier is valid until the thread terminates and can be used to uniquely identify the thread within the system. These identifiers are returned in the PROCESS_INFORMATION structure.
When specifying an application name in the lpApplicationName or lpCommandLine strings, it doesn't matter whether the application name includes the filename extension, with one exception: an MS-DOS – based or Windows-based application whose filename extension is .COM must include the .COM extension.
The calling thread can use the WaitForInputIdle function to wait until the new process has finished its initialization and is waiting for user input with no input pending. This can be useful for synchronization between parent and child processes, because CreateProcess returns without waiting for the new process to finish its initialization. For example, the creating process would use WaitForInputIdle before trying to find a window associated with the new process.
The preferred way to shut down a process is by using the ExitProcess function, because this function notifies all dynamic-link libraries (DLLs) attached to the process of the approaching termination. Other means of shutting down a process do not notify the attached DLLs. Note that when a thread calls ExitProcess, other threads of the process are terminated without an opportunity to execute any additional code (including the thread termination code of attached DLLs).
ExitProcess, ExitThread, CreateThread, CreateRemoteThread, and a process that is starting (as the result of a call by CreateProcess) are serialized between each other within a process. Only one of these events can happen in an address space at a time. This means the following restrictions hold:
The created process remains in the system until all threads within the process have terminated and all handles to the process and any of its threads have been closed through calls to CloseHandle. The handles for both the process and the main thread must be closed through calls to CloseHandle. If these handles are not needed, it is best to close them immediately after the process is created.
When the last thread in a process terminates, the following events occur:
If the current directory on drive C is \MSVC\MFC, there is an environment variable called =C: whose value is C:\MSVC\MFC. As noted in the previous description of lpEnvironment, such current directory information for a system's drives does not automatically propagate to a new process when the CreateProcess function's lpEnvironment parameter is non-NULL. An application must manually pass the current directory information to the new process. To do so, the application must explicitly create the =X environment variable strings, get them into alphabetical order (because the system uses a sorted environment), and then put them into the environment block specified by lpEnvironment. Typically, they will go at the front of the environment block, due to the previously mentioned environment block sorting.
One way to obtain the current directory variable for a drive X is to call GetFullPathName("X:",. .). That avoids an application having to scan the environment block. If the full path returned is X:\, there is no need to pass that value on as environment data, since the root directory is the default current directory for drive X of a new process.
The handle returned by the CreateProcess function has PROCESS_ALL_ACCESS access to the process object.
The current directory specified by the lpcurrentDirectory parameter is the current directory for the child process. The current directory specified in item 2 under the lpCommandLine parameter is the current directory for the parent process.
Windows NT: When a process is created with CREATE_NEW_PROCESS_GROUP specified, an implicit call to SetConsoleCtrlHandler(NULL,TRUE) is made on behalf of the new process; this means that the new process has ctrl+c disabled. This lets good shells handle ctrl+c themselves, and selectively pass that signal on to sub-processes. ctrl+break is not disabled, and may be used to interrupt the process/process group.
Windows CE: The name of the module to execute must be specified by the lpApplicationName parameter. Windows CE does not support passing NULL for lpApplicationName. The execution module cannot be specified in the command line string.
Windows CE searches the directories indicated by the lpApplicationName parameter in the following order:
The following parameters are not supported and require the following settings:
For Windows CE version 1.0, the dwCreationFlags parameter only supports the following values: CREATE_SUSPENDED and zero.
For Windows CE version 2.0, the dwCreationFlags parameter only supports the following values: CREATE_SUSPENDED, DEBUG_PROCESS, DEBUG_ONLY_THIS_PROCESS and zero.
Priority classes for processes are not supported.
The loader has a limited search path.
Windows NT: Requires version 3.1 or later.
Windows: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winbase.h.
Import Library: Use kernel32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT.
Processes and Threads Overview, Process and Thread Functions, AllocConsole, CloseHandle, CreateRemoteThread, CreateThread, ExitProcess, ExitThread, GenerateConsoleCtrlEvent, GetCommandLine, GetEnvironmentStrings, GetExitCodeProcess, GetFullPathName, GetStartupInfo, GetSystemDirectory, GetWindowsDirectory, LoadModule, OpenProcess, PROCESS_INFORMATION, ResumeThread, SECURITY_ATTRIBUTES, SetConsoleCtrlHandler, SetErrorMode, STARTUPINFO, TerminateProcess, WaitForInputIdle, WaitForDebugEvent, WinExec