Whamcloud - gitweb
LU-14034 hsm: add PID file handling to lhsmtool_posix
[fs/lustre-release.git] / lustre / utils / pid_file.c
1 /*
2  * LGPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as
8  * published by the Free Software Foundation; either version 2.1 of the
9  * License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful, but
12  * WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library. If not, see <http://www.gnu.org/licenses/>.
18  *
19  * LGPL HEADER END
20  *
21  * Copyright 2020, DataDirect Networks Storage.
22  */
23 #include <stddef.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include "pid_file.h"
30
31 int create_pid_file(const char *path)
32 {
33         char buf[3 * sizeof(long long) + 2];
34         size_t buf_len;
35         int fd = -1;
36         int rc2;
37
38         fd = open(path, O_RDWR|O_CREAT|O_CLOEXEC, 0600);
39         if (fd < 0) {
40                 fprintf(stderr, "%s: cannot open '%s': %s\n",
41                         program_invocation_short_name, path, strerror(errno));
42                 return -1;
43         }
44
45         struct flock fl = {
46                 .l_type = F_WRLCK,
47                 .l_whence = SEEK_SET,
48         };
49
50         rc2 = fcntl(fd, F_SETLK, &fl);
51         if (rc2 < 0) {
52                 fprintf(stderr, "%s: cannot lock '%s': %s\n",
53                         program_invocation_short_name, path, strerror(errno));
54                 goto out;
55         }
56
57         rc2 = ftruncate(fd, 0);
58         if (rc2 < 0) {
59                 fprintf(stderr, "%s: cannot truncate '%s': %s\n",
60                         program_invocation_short_name, path, strerror(errno));
61                 goto out;
62         }
63
64         buf_len = snprintf(buf, sizeof(buf), "%lld\n", (long long)getpid());
65         rc2 = write(fd, buf, buf_len);
66         if (rc2 < 0) {
67                 fprintf(stderr, "%s: cannot write '%s': %s\n",
68                         program_invocation_short_name, path, strerror(errno));
69                 goto out;
70         }
71 out:
72         if (rc2 < 0 && !(fd < 0)) {
73                 close(fd);
74                 fd = -1;
75         }
76
77         return fd;
78 }