限定一个程序多次运行,

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值