What's the fastest way using lsof to find a single open file?

前端 未结 4 769
再見小時候
再見小時候 2021-01-05 16:13

I\'m trying to test a single file if it is open using lsof. Is there a faster way than this?

$result = exec(\'lsof | grep filename | wc -l\');

if($result &         


        
4条回答
  •  迷失自我
    2021-01-05 17:07

    Well, you can skip wc and use the return value of grep (grep returns 0 (i.e. success) if it detects the pattern and 1 (i.e. not-success) if it does not detect the pattern):

    if lsof | grep filename > /dev/null; then
        # filename is in output of lsof
    fi
    

    You can improve this a bit by using grep's -l flag:

    if lsof | grep -l filename > /dev/null; then
    ...
    

    This tells grep to stop looking once it detects it's first match.

提交回复
热议问题