Skip to content

Instantly share code, notes, and snippets.

@schneems

schneems/pipe.md Secret

Last active June 8, 2016 17:30
Show Gist options
  • Save schneems/1e50a78b64a7920c503b319d6112166b to your computer and use it in GitHub Desktop.
Save schneems/1e50a78b64a7920c503b319d6112166b to your computer and use it in GitHub Desktop.

Update

Looks like this is totally the wrong approach. It was fun though. Think sockets are overkill for this specific use case. Especially since we would need to open them without knowing if they'll be used (including on windows systems etc). The current approach restarting a listener per-process seems to work.

Original

Goal is to communicate between multiple processes. There is a parent process that boots an evented file system notifier. When a file on disk is changed a callback will be executed. That part works, however when there are forks of the parent process the child processes do not get the notification. One idea was to communicate between parent and child processes using pipes. I'm new to this, so I have limited expectations of what can and cannot be done here.

Essentially when there is a change on disk I want each child process to be notified once and only once. Right now i'm stuck on getting a write to a pipe to show up in multiple child processes. For example I have this code

reader, writer = IO.pipe

def boot(reader)
  puts "Reading Ready #{ Process.pid }"
  while true
    res = IO.select([reader]) # blocks

    puts "Process: #{ Process.pid }, value: #{ reader.read(1) }" if res
  end
end

fork do
  boot(reader)
  sleep 10
end

fork do
  boot(reader)
  sleep 10
end

fork do
  boot(reader)
  sleep 10
end

sleep 1
puts "Writing"
writer.write('A')
writer.write('B')

sleep 1

Ideally I would like the output to be

Reading Ready 17855
Reading Ready 17856
Reading Ready 17857
Writing
Process: 17855, value: A
Process: 17856, value: A
Process: 17857, value: A
Process: 17855, value: B
Process: 17856, value: B
Process: 17857, value: B

However it isn't, each write is only read by one process

Reading Ready 17855
Reading Ready 17856
Reading Ready 17857
Writing
Process: 17855, value: A
Process: 17855, value: B

Which makes sense. My question is do you know any ways we could essentially send a notification from a parent to a child process?

I feel like the pipe idea is the right track, but I don't know where to go from here. Any ideas?

@schneems
Copy link
Author

schneems commented Jun 8, 2016

I don't get comment notifications on gists btw.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment