gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:08:57 32 4
gpt4 key购买 nike

我有 2 个可执行文件,一个在 C 中,一个在 C# 中,并希望它们通过命名管道进行通信。
C# 应用等待连接但从未获得连接
C 应用程序尝试创建管道,但总是得到 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);
}
}

我的错误是什么

最佳答案

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

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);

关于c# - 如何使用命名管道与 C 和 C# 程序通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58505435/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com