1// +build !windows
2
3/*
4** Zabbix
5** Copyright (C) 2001-2021 Zabbix SIA
6**
7** This program is free software; you can redistribute it and/or modify
8** it under the terms of the GNU General Public License as published by
9** the Free Software Foundation; either version 2 of the License, or
10** (at your option) any later version.
11**
12** This program is distributed in the hope that it will be useful,
13** but WITHOUT ANY WARRANTY; without even the implied warranty of
14** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15** GNU General Public License for more details.
16**
17** You should have received a copy of the GNU General Public License
18** along with this program; if not, write to the Free Software
19** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20**/
21
22package pidfile
23
24import (
25	"fmt"
26	"io"
27	"os"
28	"syscall"
29)
30
31func createPidFile(pid int, path string) (file *os.File, err error) {
32	if path == "" {
33		path = "/tmp/zabbix_agent2.pid"
34	}
35
36	flockT := syscall.Flock_t{
37		Type:   syscall.F_WRLCK,
38		Whence: io.SeekStart,
39		Start:  0,
40		Len:    0,
41		Pid:    int32(pid),
42	}
43	if file, err = os.OpenFile(path, os.O_WRONLY|os.O_CREATE|syscall.O_CLOEXEC, 0644); nil != err {
44		return nil, fmt.Errorf("cannot open PID file [%s]: %s", path, err.Error())
45	}
46	if err = syscall.FcntlFlock(file.Fd(), syscall.F_SETLK, &flockT); nil != err {
47		file.Close()
48		return nil, fmt.Errorf("Is this process already running? Could not lock PID file [%s]: %s",
49			path, err.Error())
50	}
51	return
52}
53