func (l Lockfile) TryLock() error {
	name := string(l)
	if !filepath.IsAbs(string(name)) {
		panic(ErrNeedAbsPath)
	}
	tmplock, err := ioutil.TempFile(filepath.Dir(name), "")
	if err != nil {
		return err
	} else {
		defer tmplock.Close()
		defer os.Remove(tmplock.Name())
	}
	_, err = tmplock.WriteString(fmt.Sprintf("%d\n", os.Getpid()))
	if err != nil {
		return err
	}
	_ = os.Link(tmplock.Name(), name)
	fiTmp, err := os.Lstat(tmplock.Name())
	if err != nil {
		return err
	}
	fiLock, err := os.Lstat(name)
	if err != nil {
		return err
	}
	if os.SameFile(fiTmp, fiLock) {
		return nil
	}
	_, err = l.GetOwner()
	switch err {
	default:
		return err
	case nil:
		return ErrBusy
	case ErrDeadOwner, ErrInvalidPid:
	}
	err = os.Remove(name)
	if err != nil {
		return err
	}
	return l.TryLock()
}
Try to get Lockfile lock. Returns nil, if successful and and error describing the reason, it didn't work out.
Please note, that existing lockfiles containing pids of dead processes and lockfiles containing no pid at all
are deleted.
package lockfile
import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
)
type Lockfile string
var (
	ErrBusy        = errors.New("Locked by other process")  
	ErrNeedAbsPath = errors.New("Lockfiles must be given as absolute path names")
	ErrInvalidPid  = errors.New("Lockfile contains invalid pid for system")
	ErrDeadOwner   = errors.New("Lockfile contains pid of process not existent on this system anymore")
)
func New(path string) (Lockfile, error) {
	if !filepath.IsAbs(path) {
		return Lockfile(""), ErrNeedAbsPath
	}
	return Lockfile(path), nil
}
func (l Lockfile) GetOwner() (*os.Process, error) {
	name := string(l)
	content, err := ioutil.ReadFile(name)
	if err != nil {
		return nil, err
	}
	var pid int
	_, err = fmt.Sscanln(string(content), &pid)
	if err != nil {
		return nil, ErrInvalidPid
	}
	if pid > 0 {
		p, err := os.FindProcess(pid)
		if err != nil {
			return nil, err
		}
		return p, isProcessAlive(p)
	} else {
		return nil, ErrInvalidPid
	}
	panic("Not reached")
}