IPC with named pipe

Linux user would know what is a pipe, and named “|” as the pipe character. Named pipe is actually similar, the difference is, a linux pipe persist as long as the process that uses the pipe last. But a named pipe persist even if the process have closed.

Why you need a named pipe? It is actually a nice way to provide IPC to 2 processes. The coolest thing of all, It is shares file semantics, i.e you can use open() and close()

Here is how you create and use a named pipe

simple named_pipe example

Shell

1

2

3

4

5

$mkfifo/tmp/named_pipe

$echo"w00t">/tmp/named_pipe

# get w00t

$cat/tmp/named_pipe

$rm/tmp/named_pipe

Of course you can replace cat and echo with your own process. One way this is really useful is by opening the pipe in your program.

This is how you write a writer

Writer in python

Python

1

2

3

4

5

6

7

8

9

10

defwriter():

f=open("/tmp/named_pipe","w")

# BLOCKING

f.write("Hello")

# Will block reader

f.close()

# Release reader and now read

if__name__=="__main__":

writer()

this is the reader

1

2

3

4

5

6

7

8

9

def reader():

f=open("/tmp/named_pipe")

# BLOCKING

printf.read()

# Blocking until writer is closed

f.close()

if__name__=="__main__":

reader()

As you can see it shares semantic with file object, with open(), read(), write(), but with caveat.