【问题标题】:Concurrent read/write of named pipe in Java (on windows)Java中命名管道的并发读/写(在Windows上)
【发布时间】:2011-02-11 23:12:25
【问题描述】:

我正在尝试使用命名管道和 v01ver 在这个问题中描述的方法在 Windows 上提供 C# 应用程序和 Java 应用程序之间的通信:How to open a Windows named pipe from Java?

我在 Java 端遇到了一个问题,因为我有一个读取器线程一直在等待管道上的输入,当我尝试从我的主线程写入管道时,它会永远卡住。

final RandomAccessFile pipe;
try {
   pipe = new RandomAccessFile("\\\\.\\pipe\\mypipe", "rw");
}
catch (FileNotFoundException ex) {
   ex.printStackTrace();
   return;
}

Thread readerThread = new Thread(new Runnable() {
   @Override
   public void run() {
      String line = null;
      try {
         while (null != (line = pipe.readLine())) {
            System.out.println(line);
         }
      }
      catch (IOException ex) {
         ex.printStackTrace();
      }
   }
});
readerThread.start();

try { Thread.sleep(500); } catch (InterruptedException e) {}

try {
   System.out.println("Writing a message...");
   pipe.write("Hello there.\n".getBytes());
   System.out.println("Finished.");
}
catch (IOException ex) {
   ex.printStackTrace();
}

输出是:

正在写消息...
然后它永远等待。

如何在等待另一个线程中的输入时写入命名管道?

【问题讨论】:

  • ...你不能关掉也不能关掉阅读?仅当文件不在末尾时才读取,否则在 poll 阻塞队列以等待写入;并最终使用单个线程。如果您有兴趣,我可以显示一个sn-p;但是我没有像这样的带有命名管道的 xp,一个简单的套接字是 10 倍易于管理
  • 使用 JVisualVM 查看您的线程是在 O/S 级别还是在 Java 同步获取时阻塞可能会有所帮助。
  • 与使用命名管道相比,您可能会发现使用套接字更具可扩展性(无论如何,命名管道在 Windows 中都是使用套接字实现的)您将找到更多有关如何使用它们的示例(因为它们使用得更频繁) 这应该对你有帮助。
  • @Peter Lawrey:Windows 中的命名管道不是使用套接字实现的。当客户端和服务器在同一台机器上时,它们使用共享内存进行 IPC,速度非常快。
  • @Peter,Java 管道(nio 管道)是通过 Windows 上的套接字和 Linux 上的操作系统管道实现的。 Windows 原生命名管道不是套接字及其 impl。不依赖于winsock。只是 java 不使用它们,因为不可能为套接字和 windows 管道注册相同的选择器。

标签: java multithreading deadlock named-pipes


【解决方案1】:

这是管道的预期行为。它应该挂起,直到其他进程连接到管道并读取它。

【讨论】:

    【解决方案2】:

    我有同样的问题——C#/Python 应用程序和 Windows 上使用命名管道的 Java 应用程序之间的通信:

    我们有用 Java 编写的客户端代码示例,但在 String echoResponse = pipe.readLine(); 行中,tread 永远等待。

    try {
        // Connect to the pipe
        RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\testpipe", "rw");
        String echoText = "Hello word\n";
        // write to pipe
        pipe.write ( echoText.getBytes() );
        // read response
        String echoResponse = pipe.readLine();
        System.out.println("Response: " + echoResponse );
        pipe.close();
    
        } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
    

    问题解决方案: 我从这里Example Code - Named Pipes 有一个用 Python 编写的 ServerPipe 代码: 并在 Python 2.6.6 上运行它

    from ctypes import *
    
    PIPE_ACCESS_DUPLEX = 0x3
    PIPE_TYPE_MESSAGE = 0x4
    PIPE_READMODE_MESSAGE = 0x2
    PIPE_WAIT = 0
    PIPE_UNLIMITED_INSTANCES = 255
    BUFSIZE = 4096
    NMPWAIT_USE_DEFAULT_WAIT = 0
    INVALID_HANDLE_VALUE = -1
    ERROR_PIPE_CONNECTED = 535
    
    MESSAGE = "Default answer from server\0"
    szPipename = "\\\\.\\pipe\\mynamedpipe"
    
    
    def ReadWrite_ClientPipe_Thread(hPipe):
        chBuf = create_string_buffer(BUFSIZE)
        cbRead = c_ulong(0)
        while 1:
            fSuccess = windll.kernel32.ReadFile(hPipe, chBuf, BUFSIZE,
    byref(cbRead), None)
            if ((fSuccess ==1) or (cbRead.value != 0)):
                print chBuf.value
                cbWritten = c_ulong(0)
                fSuccess = windll.kernel32.WriteFile(hPipe,
                                                     c_char_p(MESSAGE),
                                                     len(MESSAGE),
                                                     byref(cbWritten),
                                                     None
                                                    )
            else:
                break
            if ( (not fSuccess) or (len(MESSAGE) != cbWritten.value)):
                print "Could not reply to the client's request from the
    pipe"
                break
            else:
                print "Number of bytes written:", cbWritten.value
    
        windll.kernel32.FlushFileBuffers(hPipe)
        windll.kernel32.DisconnectNamedPipe(hPipe)
        windll.kernel32.CloseHandle(hPipe)
        return 0
    
    def main():
        THREADFUNC = CFUNCTYPE(c_int, c_int)
        thread_func = THREADFUNC(ReadWrite_ClientPipe_Thread)
        while 1:
            hPipe = windll.kernel32.CreateNamedPipeA(szPipename,
                                                     PIPE_ACCESS_DUPLEX,
                                                     PIPE_TYPE_MESSAGE |
                                                     PIPE_READMODE_MESSAGE
    |
                                                     PIPE_WAIT,
    
    PIPE_UNLIMITED_INSTANCES,
                                                     BUFSIZE, BUFSIZE,
    
    NMPWAIT_USE_DEFAULT_WAIT,
                                                     None
                                                    )
            if (hPipe == INVALID_HANDLE_VALUE):
                print "Error in creating Named Pipe"
                return 0
    
            fConnected = windll.kernel32.ConnectNamedPipe(hPipe, None)
            if ((fConnected == 0) and (windll.kernel32.GetLastError() ==
    ERROR_PIPE_CONNECTED)):
                fConnected = 1
            if (fConnected == 1):
                dwThreadId = c_ulong(0)
                hThread = windll.kernel32.CreateThread(None, 0,
    thread_func, hPipe, 0, byref(dwThreadId))
                if (hThread == -1):
                    print "Create Thread failed"
                    return 0
                else:
                    windll.kernel32.CloseHandle(hThread)
            else:
                print "Could not connect to the Named Pipe"
                windll.kernel32.CloseHandle(hPipe)
        return 0
    
    
    if __name__ == "__main__":
        main()
    

    服务器启动后,您可以使用稍作修改的Java客户端代码:

    try {
        // Connect to the pipe
        RandomAccessFile pipe = new RandomAccessFile("\\\\.\\pipe\\mynamedpipe", "rw");
        String echoText = "Hello world\n";
        // write to pipe
        pipe.write(echoText.getBytes());
    
        //String aChar;
        StringBuffer fullString = new StringBuffer();
    
        while(true){
            int charCode = pipe.read();
            if(charCode == 0) break;
            //aChar = new Character((char)charCode).toString();
            fullString.append((char)charCode);
        }
    
        System.out.println("Response: " + fullString);
        pipe.close();
    }
    catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    它在 NetBeans 6.9.1 中运行良好。

    【讨论】:

    • 好吧,如果你的服务器写了一个空字节终止的消息,那么 readLine() 函数没有返回也就不足为奇了。它正在等待来自您的服务器的“\n\r”。我也不会在生产代码中使用 read() 方法。使用 byte[] barr = new byte[1024];计数 = pipe.read(barr);查看方法,并确保不要期望服务器一次返回整个消息。
    • 这不是答案。它应该作为一个单独的问题发布。
    【解决方案3】:

    我想RandomAccessFile 在这里不是正确的 API。在 Java 端尝试 FileInputStream + FileOutputStream。但这只是一个猜测,因为我上次使用 Windows API 是在命名管道还不存在的时候。

    【讨论】:

    • 是的,RandomAccessFile 对管道的抽象是完全错误的。
    • ŭlo,您无法使用 2 个单独的读写描述符打开文件。如果您需要同时读取和写入,RadndomAccessFile 是您的最佳选择。
    【解决方案4】:

    别担心,使用RandomAccessFile 访问命名管道 是正确的。命名管道是一个文件系统对象。在 Linux/Unix 下,它也被称为“fifo”。这些对象就像文件一样可读。 (与 Java Pipe 类抽象的进程之间使用的管道不同)。

    但是,我发现您的程序存在两个问题。我目前无法对其进行测试,因为我需要您的测试服务器(请随意发布)。您的阅读器线程等待来自另一端(即服务器)的答案。它使用 readLine(),我会使用不同的方法(用于调试逐个字符读取字符可能是最好的)。

    使用 Java(没有 JNI),您实际上无法创建命名管道(服务器端)。使用 RandomAccessFile 使用的通用方法打开命名管道,您将获得可以是单向或双工的字节类型流。

    顺便说一句:JTDS(SQL Server 的免费 JDBC 驱动程序)可以选择使用命名管道访问 SQL Server,甚至通过网络。它使用的正是RandomAccessFile 方法。

    BTW2:在较旧的 MS SQL Server 安装介质上有一个 makepipe.exe 测试服务器,但是我没有找到获取该文件的可信来源。

    【讨论】:

    • 我真的不明白如何使用管道进行随机访问,你能添加一些示例代码吗?
    • 您不能进行随机访问(当然只能跳过),但该类仍然是从命名管道读取和写入的类。
    【解决方案5】:

    我不熟悉 JAVA,我的 C# 也很初级。但是,我通过打开重叠 IO 的管道修复了多线程 C++ 客户端的类似问题。在我这样做之前,Windows 会序列化读取和写入,从而有效地导致不满足(阻塞)的 ReadFile 阻止后续 WriteFile 完成,直到读取完成。

    CreateFile function
    FILE_FLAG_OVERLAPPED

    【讨论】:

    • Java 没有任何简单的方法可以将特定标志传递给 CreateFile(除非您执行一堆 JNI)。
    猜你喜欢
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多