1

Is there a way to hold a lock a unix port using netcat or some other command?

I want to do something like this:

set -e;
nc -lock 8000 &  # this needs to fail if another process holds the lock
wait;
my-proc  # start my process

how can I do this?

1

Abstract unix socket (man 7 unix):

  • abstract: an abstract socket address is distinguished (from a pathname socket) by the fact that sun_path[0] is a null byte ('\0'). The socket's address in this namespace is given by the additional bytes in sun_path that are covered by the specified length of the address structure. (Null bytes in the name have no special significance.) The name has no connection with filesystem pathnames. [...]

Its main interest here is that this socket doesn't stay around when the process which created it dies. Luckily socat provides an ABSTRACT-LISTEN method specifically for abstract sockets (avoiding having to handle '\0' in parameters and shell). Thus allowing to implement this python method in shell:

#!/bin/sh

socat ABSTRACT-LISTEN:/myownapplock - >/dev/null &
socatpid=$!

sleep 2 # wait for socat to have executed and be listening or have failed
if pgrep -P $$ '^socat$'; then
    locked=yes
else
    locked=no
    echo >&2 'Lock failed.'
    exit 1
fi

my-proc

kill $socatpid # cleanup once my-proc is done

Running the same code a 2nd time will fail. I'm sure the sleep 2 can be improved, but this code is still race-free (as long as socat takes less than 2 seconds to start). The abstract socket can be seen for example with netstat -xlp|fgrep @/myownapplock.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.