Skip to content

Instantly share code, notes, and snippets.

@skseth
Last active April 4, 2019 02:30
Show Gist options
  • Select an option

  • Save skseth/16a2fc5cfdbf58adc2021a5677e72ecc to your computer and use it in GitHub Desktop.

Select an option

Save skseth/16a2fc5cfdbf58adc2021a5677e72ecc to your computer and use it in GitHub Desktop.

Revisions

  1. skseth revised this gist Apr 4, 2019. 1 changed file with 35 additions and 0 deletions.
    35 changes: 35 additions & 0 deletions lock.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,35 @@

    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.RandomAccessFile;
    import java.nio.ByteBuffer;
    import java.nio.channels.Channels;
    import java.nio.channels.FileChannel;
    import java.nio.channels.FileLock;
    import java.nio.channels.WritableByteChannel;
    import java.nio.file.Files;
    import java.io.Console;

    public class lock {
    public static void main(final String[] args) throws Exception {
    // Read from file
    Console c = System.console();
    final File inputFile = new File("test.lock");
    FileChannel fc;
    FileLock fl;
    try (final RandomAccessFile raf = new RandomAccessFile(inputFile, "rw")) {
    fc = raf.getChannel();
    c.format("\nPress ENTER to proceed.\n");
    c.readLine();
    fl = fc.tryLock();
    c.format("\nPress ENTER to proceed.\n");
    c.readLine();
    if (fl == null) {
    System.out.println("failed to acquire lock");
    // Failed to acquire lock
    }
    }

    }

    }
  2. skseth created this gist Apr 4, 2019.
    34 changes: 34 additions & 0 deletions lock.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    package main

    import (
    "bufio"
    "fmt"
    "io"
    "os"
    "syscall"
    )

    func main() {
    var err error
    mode := syscall.O_CREAT | syscall.O_RDWR
    lockFile, err := os.OpenFile("test.lock", mode, 0666)
    if err != nil {
    fmt.Print("failed to open lockfile")
    }

    lock := syscall.Flock_t{
    Start: 0,
    Len: 0,
    Type: syscall.F_WRLCK,
    Whence: io.SeekStart,
    }

    err = syscall.FcntlFlock(lockFile.Fd(), syscall.F_SETLK, &lock)

    if err != nil {
    fmt.Print("failed to acquire lock")
    } else {
    fmt.Print("Press 'Enter' to continue...")
    bufio.NewReader(os.Stdin).ReadBytes('\n')
    }
    }