简体   繁体   English

使用flock时是否需要锁定文件是全局的

[英]Does lock file when using flock need to be global

I am setting up cron job for single instance. 我正在为单个实例设置cron作业。 Does the lock below need to be global? 下面的锁是否需要全局锁? I believe so, in order that it stays in scope until the program finishes. 我相信是这样,以便在程序完成之前将其保留在范围内。 Or at least outside of try/except block. 或至少在try / except块之外。 Also, return values should be positive from Python? 另外,Python的返回值应该是正数吗? Seems -2 returns 254 on echo $? 似乎-2在回显$上返回254? in bash. 猛扑

import time, fcntl, sys

LOCK_FILE = '/tmp/test_flock.lock'
lock = None    
def do_wait():
    print ('waiting N sec')
    time.sleep(3)

def main(argv=None):
    try:
        global lock        
        lock = open(LOCK_FILE,'w')
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        print ("got flock")
    except IOError as err:
        print ("Could not obtain lock file")
        return -2

    if argv is None:
        argv = sys.argv

    try:
        print ('entering main')
        print ('waiting')
#        raise ValueError("Error raised")
        do_wait()
        print ('done')
    except Exception as err:
        print ("Exception in main")
        return -1

if __name__ == '__main__':
    sys.exit(main())

Seems -2 returns 254 on echo $? 似乎-2在回显$上返回254? in bash. 猛扑

The Bash is interpreting the -2 as 254 probably due to how it handles negative numbers which I believe is by returning 8-bit unsigned integers. Bash将-2解释为254,可能是因为它处理负数的方式, 我相信这是通过返回8位无符号整数而实现的。

Soln: Use a postive integer number > 0 but < 256. Bash will see a return code > 0 as an error. Soln:使用一个大于0但小于256的正整数。Bash会看到返回代码> 0作为错误。

Does the lock below need to be global? 下面的锁是否需要全局锁? I believe so, in order that it stays in scope until the program finishes. 我相信是这样,以便在程序完成之前将其保留在范围内。

Ans: If there are no other conflicts with locking the file than I would say that the global lock is fine. 回答:如果与锁定文件没有其他冲突,我会说全局锁定很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM