鱼C论坛

 找回密码
 立即注册
查看: 5292|回复: 14

进程管道通信出现乱码,请指导一下

[复制链接]
发表于 2015-4-28 11:05:25 | 显示全部楼层 |阅读模式
20鱼币
如题,我在写进程通过管道通信的时候,遇到进程通信消息不稳定的情况,它的 消息内容有时候是完全正常的,有时候却会出现乱码


这里
  1. // SendMessage.cpp : 定义控制台应用程序的入口点。
  2. //

  3. #include "stdafx.h"
  4. #include <Windows.h>

  5. int _tmain(int argc, _TCHAR* argv[])
  6. {
  7.         HANDLE hRead ;
  8.         HANDLE hWrite ;

  9.         SECURITY_ATTRIBUTES sa ;
  10.         sa.nLength = sizeof(sa);
  11.         sa.lpSecurityDescriptor = NULL;
  12.         sa.bInheritHandle = TRUE ;     //指定管道句柄可被继承
  13.         BOOL bRet = CreatePipe(&hRead,&hWrite,&sa,0);        //创建匿名管道

  14.         if(bRet == TRUE){
  15.                 printf("成功创建匿名管道\n");
  16.         }else{
  17.                 printf("创建匿名管道失败,%d\n",GetLastError());
  18.         }
  19.         HANDLE hTemp = GetStdHandle(STD_OUTPUT_HANDLE);//获得本进程当前标准输出,以备将来恢复

  20.         SetStdHandle(STD_OUTPUT_HANDLE,hWrite);
  21.         STARTUPINFO si;
  22.         GetStartupInfo(&si) ;
  23.         PROCESS_INFORMATION pi;

  24.         si.dwFlags = STARTF_USESHOWWINDOW;
  25.         si.wShowWindow = TRUE ;
  26.         TCHAR szCommandLine[] = TEXT("C:\\代码\\管道通信\\Client\\Debug\\Client.exe");
  27.         bRet = CreateProcess(NULL,szCommandLine,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi);
  28.         SetStdHandle(STD_OUTPUT_HANDLE,hTemp); //恢复本进程标准输出

  29.         if (bRet == TRUE){
  30.                 printf("创建子进程成功\n");
  31.         }else{
  32.                 printf("创建子进程失败,错误代码:%d\n",GetLastError());
  33.         }
  34.         char ReadBuf[100]={0};
  35.         DWORD ReadNum;

  36.         do{
  37.                 ZeroMemory(ReadBuf,100);
  38.                 BOOL bRet = ReadFile(hRead,ReadBuf,100,&ReadNum,NULL);
  39.                 ReadBuf[ReadNum] = '\0';
  40.                 printf("从管道读取%d字节数据:[%s]\n",ReadNum,ReadBuf);
  41.         } while (bRet);
  42.         if (GetLastError() == ERROR_BROKEN_PIPE){
  43.                 printf("管道被子进程关闭\n");
  44.         }else{
  45.                 printf("读取数据错误,错误代码%d\n",GetLastError());
  46.         }
  47.         return 0;
  48. }
复制代码
消息端
  1. // Client.cpp : 定义控制台应用程序的入口点。
  2. //

  3. #include "stdafx.h"
  4. #include <Windows.h>
  5. #include <iostream>
  6. using namespace std;
  7. int _tmain(int argc, _TCHAR* argv[])
  8. {
  9.         for (int i = 0 ;i < 10 ; i++){
  10.                 printf("i = %d;",i);
  11.                 cout<<"标准输出"<<i<<endl;
  12.                 cerr<<"标准错误"<<i<<endl;
  13.         }
  14.         system("pause");
  15.         return 0;
  16. }
复制代码





附上我的源码,希望有人可以帮助一下我。

最佳答案

查看完整内容

我要去学校了,你先看

点评

我很赞同!: 5.0
我很赞同!: 5
小仙第一次给求助评分,好多鱼友连想要问的问题都没写清,自己无法达到满意答案,在这里小仙要像泡泡学习!  发表于 2015-4-28 23:37

评分

参与人数 1荣誉 +2 鱼币 +2 收起 理由
拈花小仙 + 2 + 2 优质提问 才造就 优质回答,向泡泡学习!

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-4-28 11:05:26 | 显示全部楼层
  1. #include <windows.h>
  2. #include <tchar.h>
  3. #include <stdio.h>
  4. #include <strsafe.h>

  5. #define BUFSIZE 4096

  6. HANDLE g_hChildStd_IN_Rd = NULL;
  7. HANDLE g_hChildStd_IN_Wr = NULL;
  8. HANDLE g_hChildStd_OUT_Rd = NULL;
  9. HANDLE g_hChildStd_OUT_Wr = NULL;

  10. HANDLE g_hInputFile = NULL;

  11. void CreateChildProcess(void);
  12. void WriteToPipe(void);
  13. void ReadFromPipe(void);
  14. void ErrorExit(PTSTR);

  15. int _tmain(int argc, TCHAR *argv[])
  16. {
  17.    SECURITY_ATTRIBUTES saAttr;

  18.    printf("\n->Start of parent execution.\n");

  19. // Set the bInheritHandle flag so pipe handles are inherited.

  20.    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
  21.    saAttr.bInheritHandle = TRUE;
  22.    saAttr.lpSecurityDescriptor = NULL;

  23. // Create a pipe for the child process's STDOUT.

  24.    if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0) )
  25.       ErrorExit(TEXT("StdoutRd CreatePipe"));

  26. // Ensure the read handle to the pipe for STDOUT is not inherited.

  27.    if ( ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) )
  28.       ErrorExit(TEXT("Stdout SetHandleInformation"));

  29. // Create a pipe for the child process's STDIN.

  30.    if (! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0))
  31.       ErrorExit(TEXT("Stdin CreatePipe"));

  32. // Ensure the write handle to the pipe for STDIN is not inherited.

  33.    if ( ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
  34.       ErrorExit(TEXT("Stdin SetHandleInformation"));

  35. // Create the child process.
  36.    
  37.    CreateChildProcess();

  38. // Get a handle to an input file for the parent.
  39. // This example assumes a plain text file and uses string output to verify data flow.

  40.    if (argc == 1)
  41.       ErrorExit(TEXT("Please specify an input file.\n"));

  42.    g_hInputFile = CreateFile(
  43.        argv[1],
  44.        GENERIC_READ,
  45.        0,
  46.        NULL,
  47.        OPEN_EXISTING,
  48.        FILE_ATTRIBUTE_READONLY,
  49.        NULL);

  50.    if ( g_hInputFile == INVALID_HANDLE_VALUE )
  51.       ErrorExit(TEXT("CreateFile"));

  52. // Write to the pipe that is the standard input for a child process.
  53. // Data is written to the pipe's buffers, so it is not necessary to wait
  54. // until the child process is running before writing data.

  55.    WriteToPipe();
  56.    printf( "\n->Contents of %s written to child STDIN pipe.\n", argv[1]);

  57. // Read from pipe that is the standard output for child process.

  58.    printf( "\n->Contents of child process STDOUT:\n\n", argv[1]);
  59.    ReadFromPipe();

  60.    printf("\n->End of parent execution.\n");

  61. // The remaining open handles are cleaned up when this process terminates.
  62. // To avoid resource leaks in a larger application, close handles explicitly.

  63.    return 0;
  64. }

  65. void CreateChildProcess()
  66. // Create a child process that uses the previously created pipes for STDIN and STDOUT.
  67. {
  68.    TCHAR szCmdline[]=TEXT("child");
  69.    PROCESS_INFORMATION piProcInfo;
  70.    STARTUPINFO siStartInfo;
  71.    BOOL bSuccess = FALSE;

  72. // Set up members of the PROCESS_INFORMATION structure.

  73.    ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );

  74. // Set up members of the STARTUPINFO structure.
  75. // This structure specifies the STDIN and STDOUT handles for redirection.

  76.    ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
  77.    siStartInfo.cb = sizeof(STARTUPINFO);
  78.    siStartInfo.hStdError = g_hChildStd_OUT_Wr;
  79.    siStartInfo.hStdOutput = g_hChildStd_OUT_Wr;
  80.    siStartInfo.hStdInput = g_hChildStd_IN_Rd;
  81.    siStartInfo.dwFlags |= STARTF_USESTDHANDLES;

  82. // Create the child process.
  83.    
  84.    bSuccess = CreateProcess(NULL,
  85.       szCmdline,     // command line
  86.       NULL,          // process security attributes
  87.       NULL,          // primary thread security attributes
  88.       TRUE,          // handles are inherited
  89.       0,             // creation flags
  90.       NULL,          // use parent's environment
  91.       NULL,          // use parent's current directory
  92.       &siStartInfo,  // STARTUPINFO pointer
  93.       &piProcInfo);  // receives PROCESS_INFORMATION
  94.    
  95.    // If an error occurs, exit the application.
  96.    if ( ! bSuccess )
  97.       ErrorExit(TEXT("CreateProcess"));
  98.    else
  99.    {
  100.       // Close handles to the child process and its primary thread.
  101.       // Some applications might keep these handles to monitor the status
  102.       // of the child process, for example.

  103.       CloseHandle(piProcInfo.hProcess);
  104.       CloseHandle(piProcInfo.hThread);
  105.    }
  106. }

  107. void WriteToPipe(void)

  108. // Read from a file and write its contents to the pipe for the child's STDIN.
  109. // Stop when there is no more data.
  110. {
  111.    DWORD dwRead, dwWritten;
  112.    CHAR chBuf[BUFSIZE];
  113.    BOOL bSuccess = FALSE;

  114.    for (;;)
  115.    {
  116.       bSuccess = ReadFile(g_hInputFile, chBuf, BUFSIZE, &dwRead, NULL);
  117.       if ( ! bSuccess || dwRead == 0 ) break;
  118.       
  119.       bSuccess = WriteFile(g_hChildStd_IN_Wr, chBuf, dwRead, &dwWritten, NULL);
  120.       if ( ! bSuccess ) break;
  121.    }

  122. // Close the pipe handle so the child process stops reading.

  123.    if ( ! CloseHandle(g_hChildStd_IN_Wr) )
  124.       ErrorExit(TEXT("StdInWr CloseHandle"));
  125. }

  126. void ReadFromPipe(void)

  127. // Read output from the child process's pipe for STDOUT
  128. // and write to the parent process's pipe for STDOUT.
  129. // Stop when there is no more data.
  130. {
  131.    DWORD dwRead, dwWritten;
  132.    CHAR chBuf[BUFSIZE];
  133.    BOOL bSuccess = FALSE;
  134.    HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);

  135.    for (;;)
  136.    {
  137.       bSuccess = ReadFile( g_hChildStd_OUT_Rd, chBuf, BUFSIZE, &dwRead, NULL);
  138.       if( ! bSuccess || dwRead == 0 ) break;

  139.       bSuccess = WriteFile(hParentStdOut, chBuf,
  140.                            dwRead, &dwWritten, NULL);
  141.       if (! bSuccess ) break;
  142.    }
  143. }

  144. void ErrorExit(PTSTR lpszFunction)

  145. // Format a readable error message, display a message box,
  146. // and exit from the application.
  147. {
  148.     LPVOID lpMsgBuf;
  149.     LPVOID lpDisplayBuf;
  150.     DWORD dw = GetLastError();

  151.     FormatMessage(
  152.         FORMAT_MESSAGE_ALLOCATE_BUFFER |
  153.         FORMAT_MESSAGE_FROM_SYSTEM |
  154.         FORMAT_MESSAGE_IGNORE_INSERTS,
  155.         NULL,
  156.         dw,
  157.         MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  158.         (LPTSTR) &lpMsgBuf,
  159.         0, NULL );

  160.     lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
  161.         (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR));
  162.     StringCchPrintf((LPTSTR)lpDisplayBuf,
  163.         LocalSize(lpDisplayBuf) / sizeof(TCHAR),
  164.         TEXT("%s failed with error %d: %s"),
  165.         lpszFunction, dw, lpMsgBuf);
  166.     MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK);

  167.     LocalFree(lpMsgBuf);
  168.     LocalFree(lpDisplayBuf);
  169.     ExitProcess(1);
  170. }
  171. 子进程文件
  172. #include <windows.h>
  173. #include <stdio.h>

  174. #define BUFSIZE 4096

  175. int main(void)
  176. {
  177.    CHAR chBuf[BUFSIZE];
  178.    DWORD dwRead, dwWritten;
  179.    HANDLE hStdin, hStdout;
  180.    BOOL bSuccess;

  181.    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  182.    hStdin = GetStdHandle(STD_INPUT_HANDLE);
  183.    if (
  184.        (hStdout == INVALID_HANDLE_VALUE) ||
  185.        (hStdin == INVALID_HANDLE_VALUE)
  186.       )
  187.       ExitProcess(1);

  188.    // Send something to this process's stdout using printf.
  189.    printf("\n ** This is a message from the child process. ** \n");

  190.    // This simple algorithm uses the existence of the pipes to control execution.
  191.    // It relies on the pipe buffers to ensure that no data is lost.
  192.    // Larger applications would use more advanced process control.

  193.    for (;;)
  194.    {
  195.    // Read from standard input and stop on error or no data.
  196.       bSuccess = ReadFile(hStdin, chBuf, BUFSIZE, &dwRead, NULL);
  197.       
  198.       if (! bSuccess || dwRead == 0)
  199.          break;

  200.    // Write to standard output and stop on error.
  201.       bSuccess = WriteFile(hStdout, chBuf, dwRead, &dwWritten, NULL);
  202.       
  203.       if (! bSuccess)
  204.          break;
  205.    }
  206.    return 0;
  207. }
复制代码

我要去学校了,你先看

评分

参与人数 1荣誉 +3 鱼币 +3 贡献 +2 收起 理由
拈花小仙 + 3 + 3 + 2 优质回答,点个赞!

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-4-28 13:17:39 | 显示全部楼层
正在给你写代码中,估计现在时间不够了,下午还要去学校呢。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

头像被屏蔽
发表于 2015-4-29 01:26:51 From FishC Mobile | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2015-4-29 08:24:53 | 显示全部楼层
freeparty 发表于 2015-4-28 11:05
我要去学校了,你先看

辛苦江江了,我还得研究一下你的这个代码。昨天晚上去讨论比赛的事情去了。谢谢江江啦
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

头像被屏蔽
发表于 2015-4-29 10:24:08 From FishC Mobile | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-4-29 11:37:27 | 显示全部楼层
学习
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

头像被屏蔽
发表于 2015-4-29 14:46:30 From FishC Mobile | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-4-29 17:34:06 | 显示全部楼层
学习下
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

头像被屏蔽
发表于 2015-4-30 02:09:44 From FishC Mobile | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-4-30 02:12:34 From FishC Mobile | 显示全部楼层
我只是路过打酱油的。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-4-30 21:50:07 | 显示全部楼层
哇~这个好!!!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2015-9-23 21:29:58 | 显示全部楼层
我是来领鱼币的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-1 06:53

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表