管道的问题

夜风似影 2013-08-02 03:20:06
int _tmain(int argc, _TCHAR* argv[])
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
HANDLE hRead;
HANDLE hWrite;
char ReadBuf[100];
DWORD ReadNum;
TCHAR cmdLine[] = _T("Client.exe");

bool bRet = CreatePipe(&hRead, &hWrite, NULL, 0);

if(bRet == true)
{
printf("成功创建管道\n");
}
else
{
printf("创建管道失败\n,错误代码: %d\n", GetLastError());
}

/*得到当前进程的标准输出*/
HANDLE hTemp = GetStdHandle(STD_OUTPUT_HANDLE);
/*设置标准输出到匿名管道*/
SetStdHandle(STD_OUTPUT_HANDLE, hWrite);
/*获取本进程的STARTUPINFO结构信息*/
GetStartupInfo(&si);

/*创建子进程*/
bRet = CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi);
/*恢复本进程的标准输出*/
SetStdHandle(STD_OUTPUT_HANDLE, hTemp);

if(bRet == true)
{
printf("成功创建子进程\n");
}
else
{
printf("创建子进程失败\n,错误代码: %d\n", GetLastError());
}
/*关闭写句柄*/
CloseHandle(hWrite);
/*读管道直到管道关闭*/
while(ReadFile(hRead, ReadBuf, 100, &ReadNum, NULL))
{
ReadBuf[ReadNum] = '\0';
printf("从管道[%s]读取到%d长度的信息\n", ReadBuf, ReadNum);
}


if(GetLastError() == ERROR_BROKEN_PIPE)
{
printf("管道被子进程关闭\n");
}
else
{
printf("读取管道信息失败,错误代码是: %d\n", GetLastError());
}
//pause();
return 0;
}

/*Client.exe*/
int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 0; i < 100; i++) // 发送一些数据到标准输出和标准错误
{
printf("i = %d\n", i); // 打印提示
cout << "标准输出:" << i << endl; // 打印到标准输出
cerr << "标准错误:" << i << endl; // 打印到标准错误
}

Sleep(1000);

return 0;
}
为什么ReadFile没有读到信息?只输出了标准错误
...全文
169 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
lpcads 2013-08-02
  • 打赏
  • 举报
回复
注意CreatePipe里面第三个参数,SECURITY_ATTRIBUTES sa;

	HANDLE hRead,hWrite;				//管道读、写句柄
	SECURITY_ATTRIBUTES sa;				//安全描述符

	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.bInheritHandle = TRUE;			//创建的进程继承句柄
	sa.lpSecurityDescriptor = NULL;		//使用系统默认的安全描述符
	
	if( !CreatePipe(&hRead,&hWrite,&sa,0) )
	{
		printf("创建管道失败\n,错误代码: %d\n", GetLastError());				return ;
	}
sa.bInheritHandle = TRUE; 这样句柄才会继承
赵4老师 2013-08-02
  • 打赏
  • 举报
回复
The following sample code illustrates testing for end-of-file for an asynchronous read operation:

// set up overlapped structure fields 
// to simplify this sample, we'll eschew an event handle 
gOverLapped.Offset     = 0; 
gOverLapped.OffsetHigh = 0; 
gOverLapped.hEvent     = NULL; 
 
// attempt an asynchronous read operation 
bResult = ReadFile(hFile, &inBuffer, nBytesToRead, &nBytesRead, 
    &gOverlapped) ; 
 
// if there was a problem, or the async. operation's still pending ... 
if (!bResult) 
{ 
    // deal with the error code 
    switch (dwError = GetLastError()) 
    { 
        case ERROR_HANDLE_EOF: 
        { 
            // we're reached the end of the file 
            // during the call to ReadFile 
 
            // code to handle that 
        } 
 
        case ERROR_IO_PENDING: 
        { 
            // asynchronous i/o is still in progress 
 
            // do something else for a while 
            GoDoSomethingElse() ; 
 
            // check on the results of the asynchronous read 
            bResult = GetOverlappedResult(hFile, &gOverlapped, 
                &nBytesRead, FALSE) ; 
 
            // if there was a problem ... 
            if (!bResult) 
            { 
                // deal with the error code 
                switch (dwError = GetLastError()) 
                { 
                    case ERROR_HANDLE_EOF: 
                    { 
                        // we're reached the end of the file 
                        //during asynchronous operation 
                    } 
 
                    // deal with other error cases 
                } 
            } 
        } // end case 
 
        // deal with other error cases 
 
    } // end switch 
} // end if 
 
赵4老师 2013-08-02
  • 打赏
  • 举报
回复
CreatePipe The CreatePipe function creates an anonymous pipe, and returns handles to the read and write ends of the pipe. BOOL CreatePipe( PHANDLE hReadPipe, // pointer to read handle PHANDLE hWritePipe, // pointer to write handle LPSECURITY_ATTRIBUTES lpPipeAttributes, // pointer to security attributes DWORD nSize // pipe size ); Parameters hReadPipe Pointer to the variable that receives the read handle for the pipe. hWritePipe Pointer to the variable that receives the write handle for the pipe. lpPipeAttributes Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If lpPipeAttributes is NULL, the handle cannot be inherited. Windows NT: The lpSecurityDescriptor member of the structure specifies a security descriptor for the new pipe. If lpPipeAttributes is NULL, the pipe gets a default security descriptor. nSize Specifies the buffer size for the pipe. 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 Values If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError. Remarks 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 the ReadFile 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. Windows NT: 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. QuickInfo 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. See Also Pipes Overview, Pipe Functions, ReadFile, SECURITY_ATTRIBUTES, WriteFile

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧