又是好久没写日志了,现在的日子真的不能叫生活,只能算得上是活着。现在的我,都已经不认识自己了。唉~还是贴点代码算了。
也许是自己的水平提高了,现在看自己维护的老项目的产品代码,越来越不顺眼了。于是,趁着出差这段时间,把代码里的一小部分大改了一番。其中,需要给几个进程写 daemon 程序,需要用到文件锁,所以就有了下面这段代码。
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "file_lock.h"
#define PID_BUF_LEN 16
#define LOCKMODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
int lock_file(int fd)
{
struct flock fl;
fl.l_type = F_WRLCK;
fl.l_whence = SEEK_SET;
fl.l_start = 0;
fl.l_len = 0;
return (fcntl(fd, F_SETLK, &fl));
}
int is_locked(const char *file_name)
{
int fd;
char buf[PID_BUF_LEN];
fd = open(file_name, O_RDWR | O_CREAT, LOCKMODE);
if (fd < 0)
{
printf("can't open %s: %m\n", file_name);
return -1;
}
if (lock_file(fd) < 0)
{
printf("lock %s failed: %m\n", file_name);
close(fd);
return -1;
}
ftruncate(fd, 0);
memset(buf, 0, PID_BUF_LEN);
sprintf(buf, "%d\n", getpid());
write(fd, buf, PID_BUF_LEN);
return fd;
}
都毕业两年了,还只能写出这种代码来,还说自己水平提高了,提高个屁啊!掩面泪奔……
评论