两个或多个进程同时读/写同一个进程是否可以unix socket
?
我做了一些测试。
这是我的sock_test.sh
,它产生 50 个客户端,每个客户端同时写入 5K 消息:
#! /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
然后我创建一个unix socket
并捕获该文件的所有流量sock_test.txt
:
# netcat -klU /tmp/tst.socket | tee ./sock_test.txt
最后,我运行测试脚本 ( sock_test.sh
) 并在屏幕上监视所有 50 名工作人员的工作情况。最后我检查所有消息是否已到达目的地:
# ./sock_test.sh
# sort ./sock_test.txt | uniq -c
令我惊讶的是,没有任何错误,所有 50 个工作人员都成功发送了所有 5K 消息。
我想我必须得出结论,同时写入unix sockets
可以吗?
我的并发级别是否太低而无法看到冲突?
是我的测试方法有问题吗?那么我如何正确测试它呢?
编辑
在这个问题的出色回答之后,对于那些更熟悉的人来说,python
这是我的测试台:
#! /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'])
然后在输出中您可能会观察到如下所示的行:
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
您可以看到,在某些情况下,有效负载 ( b
、d
) 不完整,但稍后会收到丢失的片段 ( c
)。简单的数学证明了这一点:
# Expected
b + d = 524288 + 524288 = 1048576
# Found b,d + extra fragment on the other check on c
b + d + c = 219258 + 219258 + 610060 = 1048576
因此同时写入unix sockets
是好的不好。
答案1
这是一条非常短的测试线。尝试大于 或 所使用的缓冲区大小的内容netcat
,socat
并从多个测试实例多次发送该字符串;这是一个sender
执行此操作的程序:
#!/usr/bin/env expect
package require Tcl 8.5
set socket [lindex $argv 0]
set character [string index [lindex $argv 1] 0]
set length [lindex $argv 2]
set repeat [lindex $argv 3]
set fh [open "| socat - UNIX-CONNECT:$socket" w]
# avoid TCL buffering screwing with our results
chan configure $fh -buffering none
set teststr [string repeat $character $length]
while {$repeat > 0} {
puts -nonewline $fh $teststr
incr repeat -1
}
然后launcher
使用长度很大的不同测试字符 (9999) 多次调用 (25) 多次 (100),希望能很好地突破任何缓冲区边界:
#!/bin/sh
# NOTE this is a very bad idea on a shared system
SOCKET=/tmp/blabla
for char in a b c d e f g h i j k l m n o p q r s t u v w x y; do
./sender -- "$SOCKET" "$char" 9999 100 &
done
wait
嗯,我不希望netcat
Centos nc
7 就足够了:
$ nc -klU /tmp/blabla > /tmp/out
然后我们在其他地方向其提供数据
$ ./launcher
现在我们/tmp/out
会很尴尬,因为没有换行符(有些东西基于换行符进行缓冲,因此换行符可能会影响测试结果,如果是这种情况,请查看setbuf(3)
基于行缓冲的潜力),因此我们需要代码来查找 a 的更改字符,并计算前一个相同字符序列的长度。
#include <stdio.h>
int main(int argc, char *argv[])
{
int current, previous;
unsigned long count = 1;
previous = getchar();
if (previous == EOF) return 1;
while ((current = getchar()) != EOF) {
if (current != previous) {
printf("%lu %c\n", count, previous);
count = 0;
previous = current;
}
count++;
}
printf("%lu %c\n", count, previous);
return 0;
}
哦,小C!让我们编译并解析我们的输出......
$ make parse
cc parse.c -o parse
$ ./parse < /tmp/out | head
49152 b
475136 a
57344 b
106496 a
49152 b
49152 a
38189 r
57344 b
57344 a
49152 b
$
呃哦。那看起来不对劲。9999 * 100
应该是 999,900 个连续的单个字母,但我们得到的却是……不是这样。a
很b
早就开始了,但看起来r
不知怎的,已经有一些早期的镜头了。这就是你的工作安排。换句话说,输出已损坏。接近文件末尾怎么样?
$ ./parse < /tmp/out | tail
8192 l
8192 v
476 d
476 g
8192 l
8192 v
8192 l
8192 v
476 l
16860 v
$ echo $((9999 * 100 / 8192))
122
$ echo $((9999 * 100 - 8192 * 122))
476
$
看起来 8192 是该系统上的缓冲区大小。无论如何!您的测试输入太短,无法运行超过缓冲区长度,并且给人一种错误的印象,即多个客户端写入都可以。增加来自客户端的数据量,您将看到混合的、因此损坏的输出。