Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Grep和pGrep组成流程_Python_Bash_Raspberry Pi3 - Fatal编程技术网

Python Grep和pGrep组成流程

Python Grep和pGrep组成流程,python,bash,raspberry-pi3,Python,Bash,Raspberry Pi3,我对bash一点也不熟悉,但我正在尝试制作一对脚本来检测 如果程序正在运行 如果python/bash脚本正在运行 我的编号1的代码是: #!/bin/bash X=$( pidof $1 ) if [ ${#X} -gt 0 ] then echo "$1 has already $X been started" else echo "$1 not started $X" fi 这非常有效,但无法检测脚本,因此我对其进行了nº2更改: X=$( pgrep -f $1 )

我对bash一点也不熟悉,但我正在尝试制作一对脚本来检测

  • 如果程序正在运行
  • 如果python/bash脚本正在运行
  • 我的编号1的代码是:

    #!/bin/bash
    
    X=$( pidof $1 )
    
    if [ ${#X} -gt 0 ]
    then
        echo "$1 has already $X been started"
    else
        echo "$1 not started $X"
    fi
    
    这非常有效,但无法检测脚本,因此我对其进行了nº2更改:

    X=$( pgrep -f $1 )
    
    起初nº2似乎可以工作,但当我终止python脚本时,我仍然得到:

    WebsocketServer has 5 length and it's already 11919 started
    
    如果我这样做,进程的PID就不会消失

    但是如果我写
    ps-ax | grepwebsocket

    11921 pts/4    S+     0:00 grep --color=auto websocket
    
    如果我启动python脚本

    WebsocketServer has 11 length and it's already 11927 11935 started
    
    发生了什么事?我是不是误用了命令


    编辑:忘记提到在终端中写入
    pgrep-f WebsocketServer
    不会返回任何结果。

    问题是脚本的参数与您正在搜索的脚本名称相同,并且
    pgrep-f
    正在查找脚本

    您可以尝试以下技巧:将名称拆分为两个参数

    checkScriptAlive websocket Server
    
    然后在脚本中,执行以下操作:

    target="$1$2"
    x=$(pgrep -f "$target")
    

    为什么要使用
    ${X}
    ,它获取存储在
    X
    中的内容的字符串长度,可能是您想
    “$X”
    来获取存储的值。
    echo“$X”
    显示了什么?@Inian他只需要长度,这样他就可以知道它是否包含任何内容。@Barmar进程的PID,每次我调用脚本时,PID都会增加2(我调用了脚本5次,其中的值为128671286912871…)使用
    pgrep
    的脚本是否在其名称中包含
    WebsocketServer
    ?我还发现使用
    pgrep-x
    而不是-f解决了问题,但是是的,问题的根源是让我发疯的东西。