BASH:从两个输入流读取的最佳架构 [英] BASH: Best architecture for reading from two input streams

查看:18
本文介绍了BASH:从两个输入流读取的最佳架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的简单脚本:

a) 不断从套接字中读取数据并将值存储在关联数组中
b) 不断从 stdin 读取值,如果它们已经存在于关联数组中,则响应 t/f

a) constantly read from a socket and store values in an associative array
b) constantly read values from stdin and respond t/f if they already exist in the associative array

一个&b 是随机事件,没有任何关联.

a & b are random events, not associated in any way.

诀窍是从两个子进程访问数组(因为将进程置于后台会产生子进程)

The trick is accessing the array from both subprocesses (since putting a process in the background spawns it as a subprocess)

我正在考虑最佳策略,并且出现了一些想法,但我想知道是否有人有更好的想法:

I'm thinking through the best strategy, and a few ideas occur, but I wonder if anyone has anything better in mind:

1) 将输入从套接字重定向到 stdin 作为一个子进程,并在一个 while 循环中处理两个输入(数据大小很小,<30 个字符,所以我猜它们会保持原子性?).
2) 读取套接字,然后在读取时使用小(0.1?)超时值的 STDIN,以模拟非阻塞 I/O.
3) UPDATE:将socket数据写入文件(实际上是让其他进程直接写入文件),然后每次请求进来检查值是否存在,处理里面的条目文件,将它们添加到数组中(使用文件锁定).

1) redirect the input from socket to stdin as a subprocess and handle both inputs in one while loop (data sizes are small, <30 characters, so I guess they will remain atomic?).
2) read the socket, then STDIN with small (0.1?) timeout values on read so as to mimic non-blocking I/O.
3) UPDATE: write the socket data to a file (actually have the other process write it directly to a file), then each time a request comes in to check if the value exists, process the entries in the file, adding them to the array (use file locking).

推荐答案

Bash 不是解决此问题的正确工具.这个问题通常使用 select(2)poll(2) 系统调用,允许你等待同时在多个文件描述符上不旋转.Bash 没有任何一个接口.

Bash is not the right tool for this. This problem is typically solved using the select(2) or poll(2) system calls, which allow you to wait on multiple file descriptors simultaneously without spinning. Bash does not have an interface to either of those.

我建议使用脚本语言,如 Python 或 Perl(无论你喜欢什么,真的),它提供了一个带有 selectpoll 的接口(例如Python 的 select 模块).

I'd recommend using a scripting language such as Python or Perl (whatever you're comfortable with, really) that provides an interface with select or poll (e.g. Python's select module).

这篇关于BASH:从两个输入流读取的最佳架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆