繁体   English   中英

如何使用命名管道通信 C 和 C# 程序

[英]How to communicate C and C# programs using named pipes

我有 2 个可执行文件,一个在 C 中,一个在 C# 中,并希望它们通过命名为 pipe 进行通信。
C# 应用程序等待连接,但从未获得连接
C 应用程序尝试创建 pipe 但总是得到ERROR_PIPE_BUSY
我显然做错了什么,但看不到。

C#代码

   public partial class MainWindow : Window
    {
        private NamedPipeServerStream pipeServer;

        public MainWindow()
        {
            InitializeComponent();
            pipeServer = new NamedPipeServerStream("TestPipe", PipeDirection.In);
            Debug.WriteLine("waiting");
            pipeServer.WaitForConnection();
            Debug.WriteLine("Connected");
        }
    }

C代码

   while (1)
   {
       _pipe = CreateNamedPipe(pipename,
         PIPE_ACCESS_OUTBOUND,
         PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,   // FILE_FLAG_FIRST_PIPE_INSTANCE is not needed but forces CreateNamedPipe(..) to fail if the pipe already exists...
         1,
         1024 * 16,
         1024 * 16,
         NMPWAIT_USE_DEFAULT_WAIT,
         NULL);
   // Break if the pipe handle is valid. 

      int err = GetLastError();
      printf("created pipe %d\n", err);
      if (_pipe != INVALID_HANDLE_VALUE)
         break;

      // Exit if an error other than ERROR_PIPE_BUSY occurs. 

      if (err != ERROR_PIPE_BUSY)
      {
         printf("Could not open pipe. GLE=%d\n", GetLastError());
         exit(-1);
      }

      // All pipe instances are busy, so wait for 20 seconds. 

      if (!WaitNamedPipe(pipename, 20000))
      {
         printf("Could not open pipe: 20 second wait timed out.");
         exit(-1);
      }
   }

我的错误是什么

您必须在创建 pipe 时设置访问权限,以克服访问被拒绝消息

PipeSecurity CreateSystemIOPipeSecurity()
{
    PipeSecurity pipeSecurity = new PipeSecurity();

     var id = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);

    // Allow Everyone read and write access to the pipe. 
    pipeSecurity.SetAccessRule(new PipeAccessRule(id, PipeAccessRights.ReadWrite, AccessControlType.Allow));

    return pipeSecurity;
}

public MainWindow()
{
    InitializeComponent();
    PipeSecurity ps = CreateSystemIOPipeSecurity();
    pipeServer = new NamedPipeServerStream(
        "TestPipe", 
        PipeDirection.InOut,
        1,
        PipeTransmissionMode.Byte,
        PipeOptions.Asynchronous,
        512,
        512,
        ps,
        System.IO.HandleInheritability.Inheritable);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM