int cm_lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)
{
struct flock lock;
lock.l_type = type; /* F_RDLCK, F_WRLCK, F_UNLCK */
lock.l_start = offset; /* byte offset, relative to l_whence */
lock.l_whence = whence; /* SEEK_SET, SEEK_CUR, SEEK_END */
lock.l_len = len; /* #bytes (0 means to EOF) */
return(fcntl(fd, cmd, &lock));
}
int main()
{
cm_check_running(PROBE_PIDFILE);
while(1)
{
sleep(5);
printf("main~~~~~~~~~~~~~main\n");
}
return 0;
}
int cm_check_running(char *file)
{
int fd, val;
char buf[16];
//printf("111111111111111\n");
if((fd = open(file, O_WRONLY | O_CREAT, CM_FILE_MODE)) < 0)
{
printf( "open file error\n");
return 1;
}
/* try and set a write lock on the entire file */
if(write_lock(fd, 0, SEEK_SET, 0) < 0)
{
if(errno == EACCES || errno == EAGAIN)
{
printf( "is already running\n");
// return CM_RUNNING;
exit(0); /* gracefully exit, daemon is already running */
}
else
{
printf( "write_lock error\n");
return CM_ERR;
}
}
// printf("2222222222222\n");
/* truncate to zero length, now that we have the lock */
if(ftruncate(fd, 0) < 0)
{
printf( "ftruncate error\n");
return CM_ERR;
}
/* and write our process ID */
sprintf(buf, "%d\n", getpid());
if(write(fd, buf, strlen(buf)) != strlen(buf))
{
printf("write error\n");
return CM_ERR;
}
/* set close-on-exec flag for descriptor */
if((val = fcntl(fd, F_GETFD, 0)) < 0)
{
printf( "fcntl F_GETFD error\n");
return CM_ERR;
}
val |= FD_CLOEXEC;
if(fcntl(fd, F_SETFD, val) < 0)
{
printf( "fcntl F_SETFD error\n");
return CM_ERR;
}
printf( "success!\n");
return CM_OK;
}
限定一个程序多次运行,
最新推荐文章于 2022-11-19 00:09:33 发布