Fork me on GitHub

linuxaddicted.de

Linux | Dev | Ops

Perl: Use of Flock

This is a small example on flock. It may help you to prevent multiple running instances of the same script. Assume you run the script via cron and it may not be finished when cron attempts to start it again. This few lines of code solve this issue.

flock example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
if ( ! open( LOCK, ">/var/run/my_app.lock" ) ) {
    print "Failed to open lock file: $!\n";
    exit(1);
}

## Create exclusive, non blocking lock: LOCK_EX(2) + LOCK_NB(4)
if ( ! flock( LOCK, 6 ) ) {
    close( LOCK );

    if ( ! open( PID, "</var/run/my_app.pid" ) ) {

        print "Failed to read PID file: $!\n";
        exit(1);
    }

    my $pid = <PID>;
    close( PID );

    print "Failed to accquire lock. Another instance (PID $pid) running!\n";
    exit(1);
}
else {
    if ( ! open( PID, ">/var/run/my_app.pid" ) ) {

        print "Failed to open pid file: $!\n";
        exit(1);
    }

    print PID $$;

    if ( ! close( PID ) ) {
        print "Failed to write PID file: $!\n";
        exit(1);
    }
}

Comments