Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

IPC using Named Pipes


  • Please log in to reply
1 reply to this topic
Ferry
  • Members
  • 37 posts
  • Last active: Mar 21 2014 10:12 AM
  • Joined: 18 May 2008

Based on the following topics I decided to share two simple scripts showing how to use IPC (Inter-process communication) based on Named Pipes.

 

http://www.autohotke...ots#entry601273

http://www.autohotke...hl= named pipe
 

 

For more information about named pipes check the following link:

http://msdn.microsof...0(v=vs.85).aspx

 

In this example I will use two scripts. One script will write (Write.ahk) a message to a pipe and one script will read (Read.ahk) this message from the pipe. You can run both scripts on the same computer or on different computers within a network but you will need to add the computer name running the write script for the read script.

 

Read.ahk:
-------------------------------------------------------------------------------------------

ComputerName = %1%
If !ComputerName
 ComputerName = .

pipe_name := "\\" ComputerName "\pipe\testpipe"

While !DllCall("WaitNamedPipe", "Str", pipe_name, "UInt", 0xffffffff)
    Sleep, 500

Loop, read, %pipe_name%
 MSgBox, %A_LoopReadLine%
 
ExitApp

-------------------------------------------------------------------------------------------

Write.ahk
-------------------------------------------------------------------------------------------

ptr := A_PtrSize ? "Ptr" : "UInt"
char_size := A_IsUnicode ? 2 : 1

pipe_name := "\\.\pipe\testpipe"

InputBox, PipeMsg, Create a pipe message, Enter a message to write in %pipe_name%.,,, 160,,,,, This is a message
If ErrorLevel
    ExitApp

pipe := CreateNamedPipe(pipe_name, 2)
If pipe = -1
    {
    MsgBox CreateNamedPipe failed.
    ExitApp
    }

DllCall("ConnectNamedPipe", ptr, pipe, ptr, 0)

;MsgBox, Connected

PipeMsg := (A_IsUnicode ? chr(0xfeff) : chr(239) chr(187) chr(191)) . PipeMsg
If !DllCall("WriteFile", ptr, pipe, "str", PipeMsg, "uint", (StrLen(PipeMsg)+1)*char_size, "uint*", 0, ptr, 0)
    MsgBox WriteFile failed: %ErrorLevel%/%A_LastError%

;MsgBox, Click OK to close handle

DllCall("CloseHandle", ptr, pipe)
ExitApp

CreateNamedPipe(Name, OpenMode=3, PipeMode=0, MaxInstances=255)
    {
    global ptr
    return DllCall("CreateNamedPipe", "str", Name, "uint", OpenMode, "uint", PipeMode, "uint", MaxInstances, "uint", 0, "uint", 0, "uint", 0, ptr, 0, ptr)
    }

-------------------------------------------------------------------------------------------

Scripts work with Unicode and ANSI. Also 32-bit and 64-bit will work fine. Let me know what you think of this.


Edited by AfterLemon, 19 March 2014 - 08:18 PM.
Code Boxes


HotKeyIt
  • Moderators
  • 7439 posts
  • Last active: Jun 22 2016 09:14 PM
  • Joined: 18 Jun 2008

Also see FileMapping.