Skip to content

Instantly share code, notes, and snippets.

@skseth skseth/lock.go
Last active Apr 4, 2019

Embed
What would you like to do?
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')
}
}
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
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.