pipe管道问题?WriteFile只有第一次有用?怎么回事?

快乐小兵 2011-11-30 09:29:27
想写一个pipe通信的程序。

A程序,通过管道不断发送1234.
B程序,scanf一个串。然后再printf出来。
但是发现A只有第一次WriteFile才有效,后面都没发送出去为什么?

A:


#include <windows.h>
#include <iostream>
#include <stdio.h>

void main()
{
SECURITY_ATTRIBUTES sa;
HANDLE hRead, hWrite, hRead2, hWrite2;

sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;
if (!CreatePipe(&hRead,&hWrite,&sa,0)) {
MessageBox(NULL, "Error On CreatePipe()", "",MB_OK);
return;
}
if (!CreatePipe(&hRead2,&hWrite2,&sa,0)) {
MessageBox(NULL, "Error On CreatePipe()", "",MB_OK);
return;
}
STARTUPINFO si;
PROCESS_INFORMATION pi;
si.cb = sizeof(STARTUPINFO);
GetStartupInfo(&si);
si.hStdError = hWrite;
si.hStdOutput = hWrite;
si.hStdInput = hRead2;//GetStdHandle(STD_INPUT_HANDLE);
//si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
if (!CreateProcess(NULL,"testData.exe"
,NULL,NULL,TRUE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi)) {
MessageBox(NULL, "Error on CreateProcess()", "", MB_OK);
return;
}
CloseHandle(hWrite);


char buffer[4096] = {0};
DWORD bytesRead, bytesRead2;
char str1[1000]= "1234\n";
WriteFile(hWrite2, str1, 6,&bytesRead2,NULL);
WriteFile(hWrite2, str1, 6,&bytesRead2,NULL); //为什么这一句没有write进管道

while (true) {

memset(buffer, 0, sizeof(buffer));
if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL)
{
MessageBox(NULL, "Error on ReadFile()", "", MB_OK);
break;
}


if (strlen(buffer) > 0)
{
printf("HaHa:%s",buffer);
//Sleep(4000);

char str1[1000]= "12345\n";
WriteFile(hWrite2, str1, 7,&bytesRead2,NULL);//为什么这一句没有write进管道
}
}
}



B:

#include <stdio.h>
#include <Windows.h>

int main()
{
char str[100]="1";
int count = 0;
while(true)
{
scanf("%s", str);
Sleep(1000);
printf("testData %d:%s\n",count, str);
fflush(stdout);
count++;
}

Sleep(4000);
return 0;
}
...全文
342 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
jinpengxx8 2012-06-16
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 的回复:]

我懂了。。。!!!
[/Quote]
请问怎么做到的啊?我也遇到同样的问题了。。。
快乐小兵 2011-11-30
  • 打赏
  • 举报
回复
我懂了。。。!!!
快乐小兵 2011-11-30
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 quwei197874 的回复:]

加上同步应该就可以了
[/Quote]

求教。怎么改?
quwei197874 2011-11-30
  • 打赏
  • 举报
回复
加上同步应该就可以了
快乐小兵 2011-11-30
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 visualeleven 的回复:]

看看WriteFile的返回值是什么,失败?GetLastError()
[/Quote]
之前试了。。WriteFile返回值,还是true。

之后的ReadFile,也能得到东西,就是后面的串是空的,只有testData:



if(!WriteFile(hWrite2, str1, 6,&bytesRead2,NULL))
MessageBox(NULL, "Error on WriteFile()", "", MB_OK);

Eleven 2011-11-30
  • 打赏
  • 举报
回复
看看WriteFile的返回值是什么,失败?GetLastError()

15,467

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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