daemon.py 文件源码

python
阅读 28 收藏 0 点赞 0 评论 0

项目:AnnotatedShadowSocks 作者: xuelangZF 项目源码 文件源码
def write_pid_file(pid_file, pid):
    """ Use the pid file to govern that the daemon is only running one instance.

    Open the pid file and set the close-on-exec flag firstly.
    Then try to acquire the exclusive lock of the pid file:
        If success, return 0 to start the daemon process.
        else, there already is a daemon process running, return -1.
    """
    import fcntl
    import stat

    # https://github.com/xuelangZF/AnnotatedShadowSocks/issues/23
    try:
        fd = os.open(pid_file, os.O_RDWR | os.O_CREAT,
                     stat.S_IRUSR | stat.S_IWUSR)
    except OSError as e:
        logging.error(e)
        return -1

    # https://github.com/xuelangZF/AnnotatedShadowSocks/issues/25
    flags = fcntl.fcntl(fd, fcntl.F_GETFD)
    assert flags != -1
    flags |= fcntl.FD_CLOEXEC
    r = fcntl.fcntl(fd, fcntl.F_SETFD, flags)
    assert r != -1

    # https://github.com/xuelangZF/AnnotatedShadowSocks/issues/26
    try:
        fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 0, 0, os.SEEK_SET)
    except IOError:
        r = os.read(fd, 32)
        if r:
            logging.error('already started at pid %s' % common.to_str(r))
        else:
            logging.error('already started')
        os.close(fd)
        return -1
    os.ftruncate(fd, 0)
    os.write(fd, common.to_bytes(str(pid)))
    return 0
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号