Is it OK for two or more processes concurrently read/write to the same unix socket
?
I've done some testing.
Here's my sock_test.sh
, which spawns 50 clients each of which concurrently write 5K messages:
#! /bin/bash --
SOC='/tmp/tst.socket'
test_fn() {
soc=$1
txt=$2
for x in {1..5000}; do
echo "${txt}" | socat - UNIX-CONNECT:"${soc}"
done
}
for x in {01..50}; do
test_fn "${SOC}" "Test_${x}" &
done
I then create a unix socket
and capture all traffic to the file sock_test.txt
:
# netcat -klU /tmp/tst.socket | tee ./sock_test.txt
Finally I run my test script (sock_test.sh
) and monitor on the screen all 50 workers doing their job. At the end I check whether all messages have reached their destination:
# ./sock_test.sh
# sort ./sock_test.txt | uniq -c
To my surprise there were no errors and all 50 workers have successfully sent all 5K messages.
I suppose I must conclude that simultaneous writing to unix sockets
is OK?
Was my concurrency level too low to see collisions?
Is there something wrong with my test method? How then I test it properly?
EDIT
Following the excellent answer to this question, for those more familiar with python
there's my test bench:
#! /usr/bin/python3 -u
# coding: utf-8
import socket
from concurrent import futures
pow_of_two = ['B','KB','MB','GB','TB']
bytes_dict = {x: 1024**pow_of_two.index(x) for x in pow_of_two}
SOC = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
SOC.connect('/tmp/tst.socket')
def write_buffer(
char: 'default is a' = 'a',
sock: 'default is /tmp/tst.socket' = SOC,
step: 'default is 8KB' = 8 * bytes_dict['KB'],
last: 'default is 2MB' = 2 * bytes_dict['MB']):
print('## Dumping to the socket: {0}'.format(sock))
while True:
in_memory = bytearray([ord(char) for x in range(step)])
msg = 'Dumping {0} bytes of {1}'
print(msg.format(step, char))
sock.sendall(bytes(str(step), 'utf8') + in_memory)
step += step
if last % step >= last:
break
def workers(concurrency=5):
chars = concurrency * ['a', 'b', 'c', 'd']
with futures.ThreadPoolExecutor() as executor:
for c in chars:
executor.submit(write_buffer, c)
def parser(chars, file='./sock_test.txt'):
with open(file=file, mode='rt', buffering=8192) as f:
digits = set(str(d) for d in range(0, 10))
def is_digit(d):
return d in digits
def printer(char, size, found, junk):
msg = 'Checking {}, Expected {:8s}, Found {:8s}, Junk {:8s}, Does Match: {}'
print(msg.format(char, size, str(found), str(junk), size == str(found)))
char, size, found, junk = '', '', 0, 0
prev = None
for x in f.read():
if is_digit(x):
if not is_digit(prev) and prev is not None:
printer(char, size, found, junk)
size = x
else:
size += x
else:
if is_digit(prev):
char, found, junk = x, 1, 0
else:
if x==char:
found += 1
else:
junk += 1
prev = x
else:
printer(char, size, found, junk)
if __name__ == "__main__":
workers()
parser(['a', 'b', 'c', 'd'])
Then in the output you may observe lines like the following:
Checking b, Expected 131072 , Found 131072 , Junk 0 , Does Match: True
Checking d, Expected 262144 , Found 262144 , Junk 0 , Does Match: True
Checking b, Expected 524288 , Found 219258 , Junk 0 , Does Match: False
Checking d, Expected 524288 , Found 219258 , Junk 0 , Does Match: False
Checking c, Expected 8192 , Found 8192 , Junk 0 , Does Match: True
Checking c, Expected 16384 , Found 16384 , Junk 0 , Does Match: True
Checking c, Expected 32768 , Found 32768 , Junk 610060 , Does Match: True
Checking c, Expected 524288 , Found 524288 , Junk 0 , Does Match: True
Checking b, Expected 262144 , Found 262144 , Junk 0 , Does Match: True
You can see that payload in some cases (b
, d
) is incomplete, however missing fragments are received later (c
). Simple math proves it:
# Expected
b + d = 524288 + 524288 = 1048576
# Found b,d + extra fragment on the other check on c
b + d + c = 219258 + 219258 + 610060 = 1048576
Therefore simultaneous writing to unix sockets
is OK NOT OK.