How to lock on Solaris 10?

On Linux I use flock lock command to execute a command with an exclusive lock.

What is the standard operating system command of Solaris 10 to do the same in a shell?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

There is no flock or similar command for Solaris. If I want to do simple locking I use mkdir as it’s a atomic operation and avoids potential race conditions with the usual check file exists/touch combination.

if ! mkdir /tmp/lockdir >/dev/null 2>&1
    echo >&2 "Lock exists exiting"
    exit 1

Solution 2

After a small Usenet discussion I use the following as a workaround for flock -n lockfile -c command:

#! /bin/bash

if [ $# != 4 -o "$1" = '-h' ] ; then
   echo "Usage: flock -n lockfile -c command" >&2
   exit 1


set -o noclobber
if 2>/dev/null : > "$lockfile" ; then
   trap 'rm -f "$lockfile"' EXIT
   $BASH -c "$command"
   exit 1

Solution 3

I’d combine the two ideas:

getLock() {
    PROG=$( basename $0 )

    if mkdir "$SHAREDLOCK" >/dev/null 2>&1
            trap 'rmdir "$SHAREDLOCK"' EXIT
            chmod 0 "$SHAREDLOCK" # discourage anyone from messing with it else the rmdir might fail
            echo >&2 "Lock ($SHAREDLOCK) exists. exiting"
            exit 1


Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply