Two programs talking
Programs on one computer can send each other messages through a named pipe, and they can share a lock so that only one copy of a program runs. This lesson starts a second copy of the program, talks to it, and shows what the lock does.
What you will learn#
- starting another program with
ProcessStartInfoandProcess, and reading what it prints, - named pipes:
NamedPipeServerStreamandNamedPipeClientStream, - a line-based protocol on top of a stream (
StreamReader/StreamWriter), - a named mutex (
Mutex) that the whole computer shares: only one copy of a program, - the same program as parent and child (
--child).
Pipes and mutexes#
A named pipe is a channel between two processes on one computer. One side is the server: it creates the pipe with a name and waits. The other side is the client: it connects to the name. Both sides get a stream and use it like a file or a socket (the tutorial Streams and compression, the tutorial Sockets). Pipes are fast and need no network and no port number.
A named mutex is a lock with a name. The first program that gets it holds it; another program that asks for the same name does not get it. Typical use: a program that must not run twice (a tray application, a database service, an installer).
The program#
# two programs talking - a named pipe between processes, and a mutex that allows only one copy
# ring ch06_processes_talk.ring the parent: it starts a second copy of this program (the child) and talks to it
# ring ch06_processes_talk.ring --child the child (the parent starts it, you do not)
load "dotnet.ring"
using {
"System"
"System.IO"
"System.IO.Pipes"
"System.Diagnostics"
"System.Threading"
}
C_PIPE = "ringdotnet_talk"
C_MUTEX = "ringdotnet_talk_single_copy"
func main
if find(sysargv,"--child") > 0
runChild()
return
ok
runParent()
# ---------------------------------------------------------------- the parent
func runParent
# 1. A named mutex is a lock that the whole computer shares. The first program that gets it is "the only copy".
oLock = new Mutex().@New([ :initiallyOwned = False, :name = C_MUTEX ])
? "1. the parent got the lock: " + yesNo(oLock.WaitOne(0)) # WaitOne(0): do not wait, just try
# 2. A named pipe server waits for a client. The pipe has a name that any program of this computer can open.
oServer = (new NamedPipeServerStream).@New([ :pipeName = C_PIPE, :direction = "InOut" ])
? nl + "2. the pipe server is listening on '" + C_PIPE + "'"
# 3. Start the child: a second copy of this program, with its output redirected so that the parent can read it
oInfo = new ProcessStartInfo().@New([ :fileName = exefilename(), :arguments = '"' + filename() + '" --child' ])
oInfo {
UseShellExecute = False
CreateNoWindow = True
RedirectStandardOutput = True
}
oChild = new Process().Start(oInfo)
oServer.WaitForConnection()
? nl + "3. the child connected"
# 4. Talk: send a request, read the answer. A line is one message.
oReader = new StreamReader(oServer)
oWriter = new StreamWriter(oServer)
oWriter.AutoFlush = True
? nl + "4. talking over the pipe:"
for cRequest in ["add 20 22","upper hello pipes","add 1 x","quit"]
oWriter.WriteLine(cRequest)
? " sent '" + cRequest + "' -> " + oReader.ReadLine()
next
# 5. The child tried to take the lock too, and printed what happened (its output was redirected to us)
cOutput = oChild.StandardOutput.ReadToEnd()
oChild.WaitForExit(NULL)
? nl + "5. the child says: " + chomp(cOutput)
? " the child's exit code: " + oChild.ExitCode
oLock.ReleaseMutex()
oServer.Dispose()
# ---------------------------------------------------------------- the child
func runChild
oLock = new Mutex().@New([ :initiallyOwned = False, :name = C_MUTEX ])
if oLock.WaitOne(0)
? "I got the lock: no other copy was running"
else
? "another copy of the program holds the lock: I am the second copy"
ok
oClient = (new NamedPipeClientStream).@New([ :serverName = ".", :pipeName = C_PIPE, :direction = "InOut" ])
oClient.Connect(5000) # wait up to 5 seconds for the server
oReader = new StreamReader(oClient)
oWriter = new StreamWriter(oClient)
oWriter.AutoFlush = True
while True
cLine = oReader.ReadLine()
if isobject(cLine) or cLine = "quit"
oWriter.WriteLine("bye")
exit
ok
oWriter.WriteLine(answer(cLine))
end
oClient.Dispose()
func answer cRequest
aWords = str2list(substr(cRequest," ",nl))
if aWords[1] = "add" and len(aWords) = 3 and isDigits(aWords[2]) and isDigits(aWords[3])
return "" + (number(aWords[2]) + number(aWords[3]))
but aWords[1] = "upper" and len(aWords) >= 2
return upper(substr(cRequest,7,len(cRequest)))
ok
return "error: I do not understand '" + cRequest + "'"
func isDigits cText
if cText = ""
return False
ok
for nIndex = 1 to len(cText)
if not isdigit(cText[nIndex])
return False
ok
next
return True
# a text without the new line at its end
func chomp cText
while right(cText,1) = char(10) or right(cText,1) = char(13)
cText = left(cText,len(cText) - 1)
end
return cText
func yesNo lValue
if lValue
return "yes"
ok
return "no"1. the parent got the lock: yes
2. the pipe server is listening on 'ringdotnet_talk'
3. the child connected
4. talking over the pipe:
sent 'add 20 22' -> 42
sent 'upper hello pipes' -> HELLO PIPES
sent 'add 1 x' -> error: I do not understand 'add 1 x'
sent 'quit' -> bye
5. the child says: another copy of the program holds the lock: I am the second copy
the child's exit code: 0This program uses a generic function (dnNew) where a class cannot be used. The lesson The generic functions explains them.
How it works#
One file, two roles#
The program starts itself a second time with the argument --child (exefilename() is the Ring executable, filename() this file). main looks at sysargv: with --child it is the child, otherwise the parent. This keeps the tutorial in one file; in real life the two programs would be different files.
The parent#
- The lock.
new Mutex().@New([ :initiallyOwned = False, :name = ... ])opens (or creates) the mutex;WaitOne(0)means try to take it, do not wait. The parent gets it. - The pipe.
NamedPipeServerStreamcreates the pipe. The constructor has many forms, so it is made with named arguments;direction = "InOut"lets both sides read and write (enums are texts). - The child.
ProcessStartInfodescribes the program to start:UseShellExecute = FalseandRedirectStandardOutput = Truelet the parent read what the child prints;CreateNoWindowhides the window.Process.Start(info)starts it. - Talking.
WaitForConnection()blocks until the child connects. After that the parent writes one line (add 20 22) and reads one line of the answer.AutoFlush = Truesends each line at once; without it the line may wait in the buffer. - The result. The child's output (
StandardOutput.ReadToEnd()), its exit code, and the lock is released.
The child#
The child tries the same mutex with WaitOne(0): it does not get it, because the parent holds it, and says so. That is exactly the check a single-instance program makes at the start: if I cannot get the lock, another copy is running — show that window and exit. Then the child connects to the pipe (Connect(5000) waits up to five seconds for the server), reads requests in a loop and answers them. quit ends the conversation.
The protocol#
A protocol is an agreement about what the messages look like. Here: one request per line, one answer per line, quit to finish, and error: ... for requests the child does not understand. Everything that goes over a pipe or a socket needs such an agreement; keep it as simple as this one.
ReadLine waits until a line arrives; a window program must not wait like this (the tutorial A chat over TCP shows how to poll). Also set time limits (Connect(5000)) so that a missing partner cannot block your program for ever.
What you learned#
Process.Startwith redirected output,- named pipes between processes,
- a named mutex for a single-instance program,
- a line protocol over a stream.
Exercises#
- Make the child answer
timewith the current time. - Let the parent start two children one after the other, each using the pipe in turn.
- Make a program that exits with a message when it cannot get the mutex, and start it twice from two terminals.
- Send a list as a line of JSON (the tutorial JSON as a tree) and parse it on the other side.