#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#define DAEMON_FILE_PID "/var/run/daemon.pid"
int main(int argc, char** argv)
{
int fd;
int ret;
struct flock lock = {
.l_type = F_WRLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0
};
char buff[32] = {0};
sprintf(buff, "%d\n", getpid());
fd = open(DAEMON_FILE_PID, O_RDWR | O_CREAT);
if (fd < 0) {
perror("failed to open file");
return -1;
}
memset(&lock, 0, sizeof(lock));
ret = fcntl(fd, F_GETLK, &lock);
if (ret < 0) {
perror("failed to get file lock info");
return -1;
}
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
ret = fcntl(fd, F_SETLK, &lock);
if (ret < 0) {
perror("failed to lock pid");
return -1;
}
ret = write(fd, buff, strlen(buff));
if (ret < 0) {
perror("failed to write pid");
return -1;
}
printf("lock file success...\r\n");
ret = getchar();
return 0;
}
08-30
956
06-01
1129
10-23
06-12
11-01
1606
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交