Last active
April 4, 2019 02:30
-
-
Save skseth/16a2fc5cfdbf58adc2021a5677e72ecc to your computer and use it in GitHub Desktop.
Revisions
-
skseth revised this gist
Apr 4, 2019 . 1 changed file with 35 additions and 0 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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 } } } } -
skseth created this gist
Apr 4, 2019 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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') } }