Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to use Unix domain socket in bash script

Tags:

bash

sockets

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

#!/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.

Is this the best way to do this?

like image 443
Cameron Ball Avatar asked Aug 12 '14 04:08

Cameron Ball


People also ask

How do I use a domain socket in UNIX?

To create a UNIX domain socket, use the socket function and specify AF_UNIX as the domain for the socket. The z/TPF system supports a maximum number of 16,383 active UNIX domain sockets at any time. After a UNIX domain socket is created, you must bind the socket to a unique file path by using the bind function.

Are UNIX domain sockets reliable?

Valid socket types in the UNIX domain are: SOCK_STREAM, for a stream-oriented socket; SOCK_DGRAM, for a datagram-oriented socket that preserves message boundaries (as on most UNIX implementations, UNIX domain datagram sockets are always reliable and don't reorder datagrams); and (since Linux 2.6.

How fast are UNIX domain sockets?

Unix domain sockets are often twice as fast as a TCP socket when both peers are on the same host. The Unix domain protocols are not an actual protocol suite, but a way of performing client/server communication on a single host using the same API that is used for clients and servers on different hosts.

Does Windows support UNIX domain sockets?

Unix sockets allow inter-process communication (IPC) between processes on the same machine. In practice that means that all recent builds of Windows 10 support Unix sockets, plus Windows 11, of course.


1 Answers

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.

like image 79
Sergey Kanaev Avatar answered Sep 20 '22 07:09

Sergey Kanaev