git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/singleinstance/single_instance_windows.go (about)

     1  package singleinstance
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  )
     7  
     8  // Lock tries to remove the lock file, if it exists.
     9  // If the file is already open by another instance of the program,
    10  // remove will fail and exit the program.
    11  func (s *SingleInstance) Lock() error {
    12  	if err := os.Remove(s.Lockfile()); err != nil && !os.IsNotExist(err) {
    13  		return ErrAlreadyRunning
    14  	}
    15  
    16  	file, err := os.OpenFile(s.Lockfile(), os.O_EXCL|os.O_CREATE, 0600)
    17  	if err != nil {
    18  		return err
    19  	}
    20  
    21  	s.file = file
    22  
    23  	return nil
    24  }
    25  
    26  // Unlock closes and removes the lockfile.
    27  func (s *SingleInstance) Unlock() error {
    28  	if err := s.file.Close(); err != nil {
    29  		return fmt.Errorf("failed to close the lock file: %w", err)
    30  	}
    31  
    32  	if err := os.Remove(s.Lockfile()); err != nil {
    33  		return fmt.Errorf("failed to remove the lock file: %w", err)
    34  	}
    35  
    36  	return nil
    37  }