windows进程函数介绍【二】

来源:互联网 发布:拍照答题软件下载 编辑:程序博客网 时间:2024/06/05 21:17

CreatePipe Function

Visual Studio 2010

Creates an anonymous pipe, and returns handles to the read and write ends of the pipe.

Syntax

C++
View ColorizedCopy to ClipboardPrint
BOOL WINAPI CreatePipe(  __out     PHANDLE hReadPipe,  __out     PHANDLE hWritePipe,  __in_opt  LPSECURITY_ATTRIBUTES lpPipeAttributes,  __in      DWORD nSize);
BOOL WINAPI CreatePipe(  __out     PHANDLE hReadPipe,  __out     PHANDLE hWritePipe,  __in_opt  LPSECURITY_ATTRIBUTES lpPipeAttributes,  __in      DWORD nSize);

Parameters

hReadPipe [out]

A pointer to a variable that receives the read handle for the pipe.

hWritePipe [out]

A pointer to a variable that receives the write handle for the pipe.

lpPipeAttributes [in, optional]

A pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. IflpPipeAttributes is NULL, the handle cannot be inherited.

The lpSecurityDescriptor member of the structure specifies a security descriptor for the new pipe. IflpPipeAttributes is NULL, the pipe gets a default security descriptor. The ACLs in the default security descriptor for a pipe come from the primary or impersonation token of the creator.

nSize [in]

The size of the buffer for the pipe, in bytes. The size is only a suggestion; the system uses the value to calculate an appropriate buffering mechanism. If this parameter is zero, the system uses the default buffer size.

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, callGetLastError.

Remarks

CreatePipe creates the pipe, assigning the specified pipe size to the storage buffer.CreatePipe also creates handles that the process uses to read from and write to the buffer in subsequent calls to theReadFile and WriteFile functions.

To read from the pipe, a process uses the read handle in a call to the ReadFile function. ReadFile returns when one of the following is true: a write operation completes on the write end of the pipe, the number of bytes requested has been read, or an error occurs.

When a process uses WriteFile to write to an anonymous pipe, the write operation is not completed until all bytes are written. If the pipe buffer is full before all bytes are written,WriteFile does not return until another process or thread uses ReadFile to make more buffer space available.

Anonymous pipes are implemented using a named pipe with a unique name. Therefore, you can often pass a handle to an anonymous pipe to a function that requires a handle to a named pipe.

To free resources used by a pipe, the application should always close handles when they are no longer needed, which is accomplished either by calling theCloseHandle function or when the process associated with the instance handles ends. Note that an instance of a pipe may have more than one handle associated with it. An instance of a pipe is always deleted when the last handle to the instance of the named pipe is closed.



WriteFile Function

Visual Studio 2010

Writes data to the specified file or input/output (I/O) device. Writes occur at the position specified by the file pointer, if the handle refers to a seeking device.

This function is designed for both synchronous and asynchronous operation. For a similar function designed solely for asynchronous operation, seeWriteFileEx.

Syntax

C++
View ColorizedCopy to ClipboardPrint
BOOL WINAPI WriteFile(  __in         HANDLE hFile,  __in         LPCVOID lpBuffer,  __in         DWORD nNumberOfBytesToWrite,  __out_opt    LPDWORD lpNumberOfBytesWritten,  __inout_opt  LPOVERLAPPED lpOverlapped);
BOOL WINAPI WriteFile(  __in         HANDLE hFile,  __in         LPCVOID lpBuffer,  __in         DWORD nNumberOfBytesToWrite,  __out_opt    LPDWORD lpNumberOfBytesWritten,  __inout_opt  LPOVERLAPPED lpOverlapped);

Parameters

hFile [in]

A handle to the file or I/O device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, communications resource, mailslot, or pipe).

The hFile parameter must have been created with the write access. For more information, seeGeneric Access Rights and File Security and Access Rights.

For asynchronous write operations, hFile can be any handle opened with theCreateFile function using the FILE_FLAG_OVERLAPPED flag or a socket handle returned by thesocket or accept function.

lpBuffer [in]

A pointer to the buffer containing the data to be written to the file or device.

This buffer must remain valid for the duration of the write operation. The caller must not use this buffer until the write operation is completed.

nNumberOfBytesToWrite [in]

The number of bytes to be written to the file or device.

A value of zero specifies a null write operation. The behavior of a null write operation depends on the underlying file system or communications technology.

Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the Remarks section.

lpNumberOfBytesWritten [out, optional]

A pointer to the variable that receives the number of bytes written when using a synchronoushFile parameter. WriteFile sets this value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results.

This parameter can be NULL only when the lpOverlapped parameter is not NULL.

For more information, see the Remarks section.

lpOverlapped [in, out, optional]

A pointer to an OVERLAPPED structure is required if the hFile parameter was opened with FILE_FLAG_OVERLAPPED, otherwise this parameter can be NULL.

For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to start writing to the file or device. This offset is specified by setting theOffset and OffsetHigh members of the OVERLAPPED structure. For anhFile that does not support byte offsets, Offset and OffsetHigh are ignored.

To write to the end of file, specify both the Offset and OffsetHigh members of the OVERLAPPED structure as 0xFFFFFFFF. This is functionally equivalent to previously calling theCreateFile function to open hFile using FILE_APPEND_DATA access.

For more information about different combinations of lpOverlapped and FILE_FLAG_OVERLAPPED, see the Remarks section and theSynchronization and File Position section.

Return Value

If the function succeeds, the return value is nonzero (TRUE).

If the function fails, or is completing asynchronously, the return value is zero (FALSE). To get extended error information, call theGetLastError function.

Note  The GetLastError code ERROR_IO_PENDING is not a failure; it designates the write operation is pending completion asynchronously. For more information, see Remarks.

Remarks

The WriteFile function returns when one of the following conditions occur:

  • The number of bytes requested is written.
  • A read operation releases buffer space on the read end of the pipe (if the write was blocked). For more information, see thePipes section.
  • An asynchronous handle is being used and the write is occurring asynchronously.
  • An error occurs.

The WriteFile function may fail with ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY whenever there are too many outstanding asynchronous I/O requests.

To cancel all pending asynchronous I/O operations, use either:

  • CancelIo—this function cancels only operations issued by the calling thread for the specified file handle.
  • CancelIoEx—this function cancels all operations issued by the threads for the specified file handle.

Use the CancelSynchronousIo function to cancel pending synchronous I/O operations.

I/O operations that are canceled complete with the error ERROR_OPERATION_ABORTED.

The WriteFile function may fail with ERROR_NOT_ENOUGH_QUOTA, which means the calling process's buffer could not be page-locked. For more information, seeSetProcessWorkingSetSize.

If part of the file is locked by another process and the write operation overlaps the locked portion,WriteFile fails.

When writing to a file, the last write time is not fully updated until all handles used for writing have been closed. Therefore, to ensure an accurate last write time, close the file handle immediately after writing to the file.

Accessing the output buffer while a write operation is using the buffer may lead to corruption of the data written from that buffer. Applications must not write to, reallocate, or free the output buffer that a write operation is using until the write operation completes. This can be particularly problematic when using an asynchronous file handle. Additional information regarding synchronous versus asynchronous file handles can be found later in theSynchronization and File Position section andSynchronous and Asynchronous I/O.

Note that the time stamps may not be updated correctly for a remote file. To ensure consistent results, use unbuffered I/O.

The system interprets zero bytes to write as specifying a null write operation andWriteFile does not truncate or extend the file. To truncate or extend a file, use theSetEndOfFile function.

Characters can be written to the screen buffer using WriteFile with a handle to console output. The exact behavior of the function is determined by the console mode. The data is written to the current cursor position. The cursor position is updated after the write operation. For more information about console handles, seeCreateFile.

When writing to a communications device, the behavior of WriteFile is determined by the current communication time-out as set and retrieved by using theSetCommTimeouts and GetCommTimeouts functions. Unpredictable results can occur if you fail to set the time-out values. For more information about communication time-outs, seeCOMMTIMEOUTS.

Although a single-sector write is atomic, a multi-sector write is not guaranteed to be atomic unless you are using a transaction (that is, the handle created is a transacted handle; for example, a handle created usingCreateFileTransacted). Multi-sector writes that are cached may not always be written to the disk right away; therefore, specify FILE_FLAG_WRITE_THROUGH inCreateFile to ensure that an entire multi-sector write is written to the disk without potential caching delays.

If you write directly to a volume that has a mounted file system, you must first obtain exclusive access to the volume. Otherwise, you risk causing data corruption or system instability, because your application's writes may conflict with other changes coming from the file system and leave the contents of the volume in an inconsistent state. To prevent these problems, the following changes have been made in Windows Vista and later:

  • A write on a volume handle will succeed if the volume does not have a mounted file system, or if one of the following conditions is true:
    • The sectors to be written to are boot sectors.
    • The sectors to be written to reside outside of file system space.
    • You have explicitly locked or dismounted the volume by using FSCTL_LOCK_VOLUME or FSCTL_DISMOUNT_VOLUME.
    • The volume has no actual file system. (In other words, it has a RAW file system mounted.)
  • A write on a disk handle will succeed if one of the following conditions is true:
    • The sectors to be written to do not fall within a volume's extents.
    • The sectors to be written to fall within a mounted volume, but you have explicitly locked or dismounted the volume by usingFSCTL_LOCK_VOLUME or FSCTL_DISMOUNT_VOLUME.
    • The sectors to be written to fall within a volume that has no mounted file system other than RAW.

There are strict requirements for successfully working with files opened with CreateFile using FILE_FLAG_NO_BUFFERING. For details see File Buffering.

If hFile was opened with FILE_FLAG_OVERLAPPED, the following conditions are in effect:

  • The lpOverlapped parameter must point to a valid and unique OVERLAPPED structure, otherwise the function can incorrectly report that the write operation is complete.
  • The lpNumberOfBytesWritten parameter should be set to NULL. To get the number of bytes written, use theGetOverlappedResult function. If the hFile parameter is associated with an I/O completion port, you can also get the number of bytes written by calling theGetQueuedCompletionStatus function.

Synchronization and File Position

If hFile is opened with FILE_FLAG_OVERLAPPED, it is an asynchronous file handle; otherwise it is synchronous. The rules for using theOVERLAPPED structure are slightly different for each, as previously noted.

Note  If a file or device is opened for asynchronous I/O, subsequent calls to functions such asWriteFile using that handle generally return immediately, but can also behave synchronously with respect to blocked execution. For more information, seeOnlinehttp://support.microsoft.com/kb/156932.

Considerations for working with asynchronous file handles:

  • WriteFile may return before the write operation is complete. In this scenario,WriteFile returns FALSE and the GetLastError function returns ERROR_IO_PENDING, which allows the calling process to continue while the system completes the write operation.
  • The lpOverlapped parameter must not be NULL and should be used with the following facts in mind:
    • Although the event specified in the OVERLAPPED structure is set and reset automatically by the system, the offset that is specified in theOVERLAPPED structure is not automatically updated.
    • WriteFile resets the event to a nonsignaled state when it begins the I/O operation.
    • The event specified in the OVERLAPPED structure is set to a signaled state when the write operation is complete; until that time, the write operation is considered pending.
    • Because the write operation starts at the offset that is specified in the OVERLAPPED structure, and WriteFile may return before the system-level write operation is complete (write pending), neither the offset nor any other part of the structure should be modified, freed, or reused by the application until the event is signaled (that is, the write completes).

Considerations for working with synchronous file handles:

  • If lpOverlapped is NULL, the write operation starts at the current file position andWriteFile does not return until the operation is complete, and the system updates the file pointer beforeWriteFile returns.
  • If lpOverlapped is not NULL, the write operation starts at the offset that is specified in theOVERLAPPED structure and WriteFile does not return until the write operation is complete. The system updates theOVERLAPPED offset before WriteFile returns.

For more information, see CreateFile and Synchronous and Asynchronous I/O.

Pipes

If an anonymous pipe is being used and the read handle has been closed, when WriteFile attempts to write using the pipe's corresponding write handle, the function returns FALSE andGetLastError returns ERROR_BROKEN_PIPE.

If the pipe buffer is full when an application uses the WriteFile function to write to a pipe, the write operation may not finish immediately. The write operation will be completed when a read operation (using theReadFile function) makes more system buffer space available for the pipe.

When writing to a nonblocking, byte-mode pipe handle with insufficient buffer space,WriteFile returns TRUE with *lpNumberOfBytesWritten < nNumberOfBytesToWrite.

For more information about pipes, see Pipes.

Transacted Operations

If there is a transaction bound to the file handle, then the file write is transacted. For more information, seeAbout Transactional NTFS.

Examples

For some examples, see Creating and Using a Temporary File and Opening a File for Reading or Writing.

The following C++ example shows how to align sectors for unbuffered file writes. TheSize variable is the size of the original data block you are interested in writing to the file. For additional rules regarding unbuffered file I/O, seeFile Buffering.

View ColorizedCopy to ClipboardPrint
#include <windows.h>    #define ROUND_UP_SIZE(Value,Pow2) \     ((SIZE_T) ((((ULONG)(Value)) + (Pow2) - 1) \     & (~(((LONG)(Pow2)) - 1))))    #define ROUND_UP_PTR(Ptr,Pow2) \     ((void *) ((((ULONG_PTR)(Ptr)) + (Pow2) - 1) \     & (~(((LONG_PTR)(Pow2)) - 1))))      void main()  {  // Function code        DWORD BytesPerSector; // obtained from the GetFreeDiskSpace function.      DWORD Size; // buffer size of your data to write    // ... obtain data here       // Ensure you have one more sector than Size would require.     SIZE_T SizeNeeded = BytesPerSector + ROUND_UP_SIZE(Size, BytesPerSector);          // Replace this statement with any allocation routine.     LPBYTE Buffer = (LPBYTE) malloc(SizeNeeded);       // Error checking of your choice.     if ( !Buffer )      {       goto cleanup;     }       // Actual alignment happens here.     void * BufferAligned = ROUND_UP_PTR(Buffer, BytesPerSector);       // Add code using BufferAligned here.       cleanup:       if ( Buffer )      {        // Replace with corresponding free routine.        free(Buffer);     }    }  
#include <windows.h>#define ROUND_UP_SIZE(Value,Pow2) \   ((SIZE_T) ((((ULONG)(Value)) + (Pow2) - 1) \   & (~(((LONG)(Pow2)) - 1))))#define ROUND_UP_PTR(Ptr,Pow2) \   ((void *) ((((ULONG_PTR)(Ptr)) + (Pow2) - 1) \   & (~(((LONG_PTR)(Pow2)) - 1))))void main(){// Function code    DWORD BytesPerSector; // obtained from the GetFreeDiskSpace function.    DWORD Size; // buffer size of your data to write// ... obtain data here   // Ensure you have one more sector than Size would require.   SIZE_T SizeNeeded = BytesPerSector + ROUND_UP_SIZE(Size, BytesPerSector);      // Replace this statement with any allocation routine.   LPBYTE Buffer = (LPBYTE) malloc(SizeNeeded);   // Error checking of your choice.   if ( !Buffer )    {     goto cleanup;   }   // Actual alignment happens here.   void * BufferAligned = ROUND_UP_PTR(Buffer, BytesPerSector);   // Add code using BufferAligned here. cleanup:   if ( Buffer )    {      // Replace with corresponding free routine.      free(Buffer);   }}



ReadFile Function

Visual Studio 2010

Reads data from the specified file or input/output (I/O) device. Reads occur at the position specified by the file pointer if supported by the device.

This function is designed for both synchronous and asynchronous operations. For a similar function designed solely for asynchronous operation, seeReadFileEx.

Syntax

C++
View ColorizedCopy to ClipboardPrint
BOOL WINAPI ReadFile(  __in         HANDLE hFile,  __out        LPVOID lpBuffer,  __in         DWORD nNumberOfBytesToRead,  __out_opt    LPDWORD lpNumberOfBytesRead,  __inout_opt  LPOVERLAPPED lpOverlapped);
BOOL WINAPI ReadFile(  __in         HANDLE hFile,  __out        LPVOID lpBuffer,  __in         DWORD nNumberOfBytesToRead,  __out_opt    LPDWORD lpNumberOfBytesRead,  __inout_opt  LPOVERLAPPED lpOverlapped);

Parameters

hFile [in]

A handle to the device (for example, a file, file stream, physical disk, volume, console buffer, tape drive, socket, communications resource, mailslot, or pipe).

The hFile parameter must have been created with read access. For more information, seeGeneric Access Rights and File Security and Access Rights.

For asynchronous read operations, hFile can be any handle that is opened with the FILE_FLAG_OVERLAPPED flag by theCreateFile function, or a socket handle returned by the socket or accept function.

lpBuffer [out]

A pointer to the buffer that receives the data read from a file or device.

This buffer must remain valid for the duration of the read operation. The caller must not use this buffer until the read operation is completed.

nNumberOfBytesToRead [in]

The maximum number of bytes to be read.

lpNumberOfBytesRead [out, optional]

A pointer to the variable that receives the number of bytes read when using a synchronoushFile parameter. ReadFile sets this value to zero before doing any work or error checking. Use NULL for this parameter if this is an asynchronous operation to avoid potentially erroneous results.

This parameter can be NULL only when the lpOverlapped parameter is not NULL.

For more information, see the Remarks section.

lpOverlapped [in, out, optional]

A pointer to an OVERLAPPED structure is required if the hFile parameter was opened with FILE_FLAG_OVERLAPPED, otherwise it can be NULL.

If hFile is opened with FILE_FLAG_OVERLAPPED, the lpOverlapped parameter must point to a valid and uniqueOVERLAPPED structure, otherwise the function can incorrectly report that the read operation is complete.

For an hFile that supports byte offsets, if you use this parameter you must specify a byte offset at which to start reading from the file or device. This offset is specified by setting theOffset and OffsetHigh members of the OVERLAPPED structure. For anhFile that does not support byte offsets, Offset and OffsetHigh are ignored.

For more information about different combinations of lpOverlapped and FILE_FLAG_OVERLAPPED, see the Remarks section and theSynchronization and File Position section.

Return Value

If the function succeeds, the return value is nonzero (TRUE).

If the function fails, or is completing asynchronously, the return value is zero (FALSE). To get extended error information, call theGetLastError function.

Note  The GetLastError code ERROR_IO_PENDING is not a failure; it designates the read operation is pending completion asynchronously. For more information, see Remarks.

Remarks

The ReadFile function returns when one of the following conditions occur:

  • The number of bytes requested is read.
  • A write operation completes on the write end of the pipe.
  • An asynchronous handle is being used and the read is occurring asynchronously.
  • An error occurs.

If the ReadFile function attempts to read past the end of the file, the function returns zero, andGetLastError returns ERROR_HANDLE_EOF.

The ReadFile function may fail with ERROR_INVALID_USER_BUFFER or ERROR_NOT_ENOUGH_MEMORY whenever there are too many outstanding asynchronous I/O requests.

To cancel all pending asynchronous I/O operations, use either:

  • CancelIo—this function only cancels operations issued by the calling thread for the specified file handle.
  • CancelIoEx—this function cancels all operations issued by the threads for the specified file handle.

Use CancelSynchronousIo to cancel pending synchronous I/O operations.

I/O operations that are canceled complete with the error ERROR_OPERATION_ABORTED.

The ReadFile function may fail with ERROR_NOT_ENOUGH_QUOTA, which means the calling process's buffer could not be page-locked. For additional information, seeSetProcessWorkingSetSize.

If part of a file is locked by another process and the read operation overlaps the locked portion, this function fails.

Accessing the input buffer while a read operation is using the buffer may lead to corruption of the data read into that buffer. Applications must not read from, write to, reallocate, or free the input buffer that a read operation is using until the read operation completes. This can be particularly problematic when using an asynchronous file handle. Additional information regarding synchronous versus asynchronous file handles can be found in theSynchronization and File Position section and in theCreateFile reference topic.

Characters can be read from the console input buffer by using ReadFile with a handle to console input. The console mode determines the exact behavior of theReadFile function. By default, the console mode is ENABLE_LINE_INPUT, which indicates thatReadFile should read until it reaches a carriage return. If you press Ctrl+C, the call succeeds, butGetLastError returns ERROR_OPERATION_ABORTED. For more information, seeCreateFile.

When reading from a communications device, the behavior of ReadFile is determined by the current communication time-out as set and retrieved by using theSetCommTimeouts and GetCommTimeouts functions. Unpredictable results can occur if you fail to set the time-out values. For more information about communication time-outs, seeCOMMTIMEOUTS.

If ReadFile attempts to read from a mailslot that has a buffer that is too small, the function returns FALSE andGetLastError returns ERROR_INSUFFICIENT_BUFFER.

There are strict requirements for successfully working with files opened with CreateFile using the FILE_FLAG_NO_BUFFERING flag. For details see File Buffering.

If hFile was opened with FILE_FLAG_OVERLAPPED, the following conditions are in effect:

  • The lpOverlapped parameter must point to a valid and unique OVERLAPPED structure, otherwise the function can incorrectly report that the read operation is complete.
  • The lpNumberOfBytesRead parameter should be set to NULL. Use the GetOverlappedResult function to get the actual number of bytes read. If thehFile parameter is associated with an I/O completion port, you can also get the number of bytes read by calling theGetQueuedCompletionStatus function.

Synchronization and File Position

If hFile is opened with FILE_FLAG_OVERLAPPED, it is an asynchronous file handle; otherwise it is synchronous. The rules for using theOVERLAPPED structure are slightly different for each, as previously noted.

Note  If a file or device is opened for asynchronous I/O, subsequent calls to functions such asReadFile using that handle generally return immediately, but can also behave synchronously with respect to blocked execution. For more information seeOnlinehttp://support.microsoft.com/kb/156932.

Considerations for working with asynchronous file handles:

  • ReadFile may return before the read operation is complete. In this scenario,ReadFile returns FALSE and the GetLastError function returns ERROR_IO_PENDING, which allows the calling process to continue while the system completes the read operation.
  • The lpOverlapped parameter must not be NULL and should be used with the following facts in mind:
    • Although the event specified in the OVERLAPPED structure is set and reset automatically by the system, the offset that is specified in theOVERLAPPED structure is not automatically updated.
    • ReadFile resets the event to a nonsignaled state when it begins the I/O operation.
    • The event specified in the OVERLAPPED structure is set to a signaled state when the read operation is complete; until that time, the read operation is considered pending.
    • Because the read operation starts at the offset that is specified in the OVERLAPPED structure, and ReadFile may return before the system-level read operation is complete (read pending), neither the offset nor any other part of the structure should be modified, freed, or reused by the application until the event is signaled (that is, the read completes).
    • If end-of-file (EOF) is detected during asynchronous operations, the call to GetOverlappedResult for that operation returns FALSE and GetLastError returns ERROR_HANDLE_EOF.

Considerations for working with synchronous file handles:

  • If lpOverlapped is NULL, the read operation starts at the current file position andReadFile does not return until the operation is complete, and the system updates the file pointer beforeReadFile returns.
  • If lpOverlapped is not NULL, the read operation starts at the offset that is specified in theOVERLAPPED structure and ReadFile does not return until the read operation is complete. The system updates theOVERLAPPED offset before ReadFile returns.
  • When a synchronous read operation reaches the end of a file, ReadFile returns TRUE and sets *lpNumberOfBytesRead to zero.

For more information, see CreateFile and Synchronous and Asynchronous I/O.

Pipes

If an anonymous pipe is being used and the write handle has been closed, when ReadFile attempts to read using the pipe's corresponding read handle, the function returns FALSE andGetLastError returns ERROR_BROKEN_PIPE.

If a named pipe is being read in message mode and the next message is longer than thenNumberOfBytesToRead parameter specifies, ReadFile returns FALSE andGetLastError returns ERROR_MORE_DATA. The remainder of the message can be read by a subsequent call to theReadFile or PeekNamedPipefunction.

If the lpNumberOfBytesRead parameter is zero when ReadFile returns TRUE on a pipe, the other end of the pipe called theWriteFile function with nNumberOfBytesToWrite set to zero.

For more information about pipes, see Pipes.

Transacted Operations

If there is a transaction bound to the file handle, then the function returns data from the transacted view of the file. A transacted read handle is guaranteed to show the same view of a file for the duration of the handle. For more information, seeAbout Transactional NTFS.

    DWORD bytesRead = 0;
    BOOL ok = ReadFile(_readHandle, buffer, length, &bytesRead, NULL);
    if (ok || GetLastError() == ERROR_BROKEN_PIPE)
        return bytesRead;

    这里读无名管道pipe成功的标志是:1:ReadFile成功;2:ReadFile失败但是写句柄已关闭

GetStartupInfo Function

Visual Studio 2010

Retrieves the contents of the STARTUPINFO structure that was specified when the calling process was created.

Syntax

C++
View ColorizedCopy to ClipboardPrint
VOID WINAPI GetStartupInfo(  __out  LPSTARTUPINFO lpStartupInfo);
VOID WINAPI GetStartupInfo(  __out  LPSTARTUPINFO lpStartupInfo);

Parameters

lpStartupInfo [out]

A pointer to a STARTUPINFO structure that receives the startup information.

Return Value

This function does not return a value.

If an error occurs, the ANSI version of this function ( GetStartupInfoA) can raise an exception. The Unicode version (GetStartupInfoW) does not fail.

Remarks

The STARTUPINFO structure was specified by the process that created the calling process. It can be used to specify properties associated with the main window of the calling process.

typedef struct _STARTUPINFO
{
   DWORD cb;            //包含STARTUPINFO结构中的字节数.如果Microsoft将来扩展该结构,它可用作版本控制手段.
                        应用程序必须将cb初始化为sizeof(STARTUPINFO)
   PSTR lpReserved;      //保留。必须初始化为N U L L
   PSTR lpDesktop;    //用于标识启动应用程序所在的桌面的名字。如果该桌面存在,新进程便与指定的桌面相关联。
                      如果桌面不存在,便创建一个带有默认属性的桌面,并使用为新进程指定的名字。
                     如果lpDesktop是NULL(这是最常见的情况),那么该进程将与当前桌面相关联
   PSTR lpTitle;    //用于设定控制台窗口的名称。如果l p Ti t l e 是N U L L ,则可执行文件的名字将用作窗口名
   DWORD dwX;       //用于设定应用程序窗口在屏幕上应该放置的位置的x 和y 坐标(以像素为单位)。
   DWORD dwY;       只有当子进程用CW_USEDEFAULT作为CreateWindow的x参数来创建它的第一个重叠窗口时,
                    才使用这两个坐标。若是创建控制台窗口的应用程序,这些成员用于指明控制台窗口的左上角

   DWORD dwXSize;  //用于设定应用程序窗口的宽度和长度(以像素为单位)只有dwYsize
    DWORD dwYSize;   当子进程将C W _ U S E D E FA U LT 用作C r e a t e Wi n d o w 的
                     n Wi d t h参数来创建它的第一个重叠窗口时,才使用这些值。
                     若是创建控制台窗口的应用程序,这些成员将用于指明控制台窗口的宽度
   DWORD dwXCountChars;  //用于设定子应用程序的控制台窗口的宽度和高度(以字符为单位)
   DWORD dwYCountChars;
   DWORD dwFillAttribute;   //用于设定子应用程序的控制台窗口使用的文本和背景颜色
   DWORD dwFlags;           //请参见下一段和表4 - 7 的说明
   WORD wShowWindow;        //用于设定如果子应用程序初次调用的S h o w Wi n d o w 将S W _ S H O W D E FA U LT 作为
                              n C m d S h o w 参数传递时,该应用程序的第一个重叠窗口应该如何出现。
                              本成员可以是通常用于Show Wi n d o w 函数的任何一个S W _ *标识符
   WORD cbReserved2;        //保留。必须被初始化为0
   PBYTE lpReserved2;       //保留。必须被初始化为N U L L
   HANDLE hStdInput;        //用于设定供控制台输入和输出用的缓存的句柄。
                            按照默认设置,h S t d I n p u t 用于标识键盘缓存,
                            h S t d O u t p u t 和h S t d E r r o r用于标识控制台窗口的缓存
   HANDLE hStdOutput;
   HANDLE hStdError;
} STARTUPINFO, *LPSTARTUPINFO;
当Wi n d o w s 创建新进程时,它将使用该结构的有关成员。大多数应用程序将要求生成的应用程序仅仅使用默认值。至少应该将该结构中的所有成员初始化为零,然后将c b 成员设置为该结构的大小:
STARTUPINFO si = { sizeof(si) };
CreateProcess(...,&si,...);

表4-7 dwFlags 使用标志及含义
标志                                    含义
STARTF_USESIZE                 // 使用d w X S i z e 和d w Y S i z e 成员
STARTF_USESHOWWINDOW              //使用w S h o w Wi n d o w 成员
STARTF_USEPOSITION              //使用d w X 和d w Y 成员
STARTF_USECOUNTCHARS                //使用d w X C o u n t C h a r s 和dwYCount Chars 成员
STARTF_USEFILLATTRIBUTE          //使用d w F i l l A t t r i b u t e 成员
STARTF_USESTDHANDLES              //使用h S t d I n p u t 、h S t d O u t p u t 和h S t d E r r o r 成员
STARTF_RUN_FULLSCREEN              //强制在x 8 6 计算机上运行的控制台应用程序以全屏幕方式启动运行

另外还有两个标志,即STARTF_FORCEONFEEDBACK 和STARTF_+FORCEOFFF -EEDBACK ,当启动一个新进程时,它们可以用来控制鼠标的光标。由于Windows支持真正的多任务抢占式运行方式,因此可以启动一个应用程序,然后在进程初始化时,使用另一个程序。为了向用户提供直观的反馈信息,C r e a t e P r o c e s s 能够临时将系统的箭头光标改为一个新光标,即沙漏箭头光标:

该光标表示可以等待出现某种情况,也可以继续使用系统。当启动另一个进程时,CreateProcess函数使你能够更好地控制光标。当设定STARTF_FORCEONFEEDBACK标志时,C r e a t e P r o c e s s 并不将光标改为沙漏。

STARTF_FORCEONFEEDBACK可使CreateProcess能够监控新进程的初始化,并可根据结果来改变光标。当使用该标志来调用CreateProcess时,光标改为沙漏。过2 s 后,如果新进程没有调用G U I ,CreateProcess 将光标恢复为箭头。

如果该进程在2 s 内调用了GUI ,CreateProcess将等待该应用程序显示一个窗口。这必须在进程调用G U I 后5 s内发生。如果没有显示窗口,CreateProcess就会恢复原来的光标。如果显示了一个窗口,CreateProcess将使沙漏光标继续保留5s 。如果某个时候该应用程序调用了G e t M e s s a g e 函数,指明它完成了初始化,那么C r e a t e P r o ce s s 就会立即恢复原来的光标,并且停止监控新进程。

在结束这一节内容的介绍之前,我想讲一讲S TA RT U P I N F O 的w S h o w Wi n d o w成员。你将该成员初始化为传递给( w ) Wi n M a i n 的最后一个参数n C m d S h o w的值。该成员显示你想要传递给新进程的( w ) Wi n M a i n 函数的最后一个参数n C m d S h o w的值。它是可以传递给S h o w Wi n d o w 函数的标识符之一。通常,n C m d S h o w 的值既可以是S W _ SH O W N O R M A L ,也可以是SW_ SHOWMINNOACTIVE 。但是,它有时可以是S W _ S H O W D EFA U LT 。

当在E x p l o r e r 中启动一个应用程序时,该应用程序的( w ) Wi n M a i n 函数被调用,而S W _ SH O W N O R M A L 则作为n C m d S h o w参数来传递。如果为该应用程序创建了一个快捷方式,可以使用快捷方式的属性页来告诉系统,应用程序的窗口最初应该如何显示。图4 - 3 显示了运行No t e p a d 的快捷方式的属性页。注意,使用R u n 选项的组合框,就能够设定如何显示N o t e p a d 的窗口。

当使用E x p l o r e r 来启动该快捷方式时,E x p l o r e r 会正确地准备S TA RT U P I N FO 结构并调用C r e a t e P r o c e s s 。这时N o t e p a d 开始运行,并且为n C m d S h ow 参数将S W _ S H O W M I N N O A C T I V E传递给它的( w ) Wi n M a i n 函数。

运用这样的方法,用户能够很容易地启动一个应用程序,其主窗口可以用正常状态、最小或最大状态进行显示。

最后,应用程序可以调用下面的函数,以便获取由父进程初始化的S TA RT U P I N F O 结构的拷贝。子进程可以查看该结构,并根据该结构的成员的值来改变它的行为特性。

VOID GetStartupInfo(LPSTARTUPINFO pStartupInfo);
注意虽然Wi n d o w s 文档没有明确地说明,但是在调用G e t S t a r t I n f o 函数之前,必须像下面这样对该结构的c b 成员进行初始化:
STARTUPINFO si = { sizeof(si) };
GetStartupInfo(&si);