在 bash 脚本中使用 Unix 域套接字的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25256320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:05:45  来源:igfitidea点击:

Best way to use Unix domain socket in bash script

bashsockets

提问by Cameron Ball

I'm working on a simple bash script daemon that uses Unix domain sockets. I have a loop like this:

我正在开发一个使用 Unix 域套接字的简单 bash 脚本守护程序。我有一个这样的循环:

#!/bin/bash
while true
do
    rm /var/run/mysock.sock
    command=`nc -Ul /var/run/mysock.sock`
    echo $command > /tmp/command
done

I'm echoing the command out to /tmp/command just for debugging purposes.

我将命令回显到 /tmp/command 只是为了调试目的。

Is this the best way to do this?

这是最好的方法吗?

回答by Sergey Kanaev

Looks like I'm late to the party. Anyway, here is my suggestion I employ successfully for one-shot messages with response:

看来我参加聚会迟到了。无论如何,这是我的建议,我成功地使用了带有响应的一次性消息:

INPUT=$(mktemp -u)
mkfifo -m 600 "$INPUT"
OUTPUT=$(mktemp -u)
mkfifo -m 600 "$OUTPUT"

(cat "$INPUT" | nc -U "$SKT_PATH" > "$OUTPUT") &
NCPID=$!

exec 4>"$INPUT"
exec 5<"$OUTPUT"

echo "$POST_LINE" >&4
read -u 5 -r RESPONSE;
echo "Response: '$RESPONSE'"

Here I use two FIFOs to talk to nc (1)and fetch it's response.

在这里,我使用两个 FIFO 进行通信nc (1)并获取它的响应。