[英]How to communicate C and C# programs using named pipes
我有 2 個可執行文件,一個在 C 中,一個在 C# 中,並希望它們通過命名為 pipe 進行通信。
C# 應用程序等待連接,但從未獲得連接
C 應用程序嘗試創建 pipe 但總是得到ERROR_PIPE_BUSY
我顯然做錯了什么,但看不到。
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");
}
}
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.