守护进程+记录锁阻止程序重复运行

守护进程:

void Init_Daemon()
{
    int pid;
    pid = fork();
    if(pid > 0)         //parent
        exit(0);
    else if(pid < 0)    //error
        exit(1);

    //子进程继续执行。父进程终止
    setsid(); 

    if(pid = fork())
        exit(0);
    else if(pid < 0)
        exit(1);

    //close handle of file。此处不知道为什么
    for(int i=0; i<3; ++i)
        close(i);

    chdir("/");
    umask(0);
    return;
}

 

记录锁:

int test(int fd)
{
    struct flock   flk;
    flk.l_type   = F_WRLCK;  /* F_RDLCK, F_WRLCK, or F_UNLCK */
    flk.l_whence = SEEK_SET; /* SEEK_SET, SEEK_CUR, SEEK_END */
    flk.l_start  = 0;        /* starting offset relative to l_whence */
    flk.l_len    = 0;        /* len == 0 means "until end of file" */
    flk.l_pid    = getpid(); /* Process ID of the process holding the
                                        lock, returned with F_GETLK */
    return fcntl(fd, F_SETLK, &flk);
}

 

int fd;
    if ((fd = open(strPIDFileName, O_RDWR | O_CREAT, FILE_MODE)) < 0)
    {
        exit(1);
    }
    if(test(fd) < 0)       //返回值小于0.锁定不成功。
        return 0;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值