Skip to content

Instantly share code, notes, and snippets.

@hibariya
Last active March 3, 2024 09:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hibariya/aefede3efb12d69ad15435daf5790ddd to your computer and use it in GitHub Desktop.
Save hibariya/aefede3efb12d69ad15435daf5790ddd to your computer and use it in GitHub Desktop.
IPC example between containers with named pipes (FIFOs)
x-env: &env
- PROC_INPUT=/var/run/sample/proc-in
- PROC_OUTPUT=/var/run/sample/proc-out
- PROC_LOCK=/var/run/sample/proc.lock
volumes:
ipc:
services:
web:
image: ruby:3.1-slim
ports: ['4567:4567']
init: true
working_dir: /work
environment: *env
command: ['ruby', 'server.rb']
volumes:
- type: volume
source: ipc
target: /var/run/sample
- type: bind
source: ./web
target: /work
processor:
image: r.j3ss.co/aspell
init: true
working_dir: /work
environment: *env
entrypoint: ['/bin/ash']
command: ['/work/worker.sh']
volumes:
- type: volume
source: ipc
target: /var/run/sample
- type: bind
source: ./processor
target: /work
<html>
<head>
<meta charset="UTF-8" />
<title>demonstrating ipc with named pipes</title>
<script>
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('submit').addEventListener('click', async () => {
const res = await fetch('/process', {
method: 'POST',
body: document.getElementById('proc_input').value,
});
document.getElementById('proc_output').value = await res.text();
});
});
</script>
</head>
<body>
<textarea id="proc_input" style="width: 100%; height: 5rem;"></textarea>
<button id="submit">Send</button>
<hr />
<textarea id="proc_output" style="width: 100%; height: 20rem;"></textarea>
</body>
</html>
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'sinatra'
gem 'webrick'
end
set :static, true
set :public_folder, __dir__
set :bind, '0.0.0.0'
get '/' do
content_type 'text/html'
send_file File.join(settings.public_folder, 'index.html')
end
post '/process' do
content_type 'text/plain'
File.open ENV['PROC_LOCK'] do |lock|
lock.flock File::LOCK_EX
output = Thread.new { File.read(ENV['PROC_OUTPUT']) }
File.write ENV['PROC_INPUT'], request.body.read
output.value
end
end
Sinatra::Application.run!
#!/bin/bash
set -e
test -p "$PROC_INPUT" || mkfifo "$PROC_INPUT"
test -p "$PROC_OUTPUT" || mkfifo "$PROC_OUTPUT"
test -f "$PROC_LOCK" || touch "$PROC_LOCK"
set +e
while :
do
echo "Waiting input..."
aspell -a < "$PROC_INPUT" > "$PROC_OUTPUT"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment