Bash 如何从 PID 获取完整的脚本名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14764668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:30:46  来源:igfitidea点击:

Bash how to get full script name from PID

phpbashps

提问by user1105430

I have this php function that checks the script's name from the given PID, and compares it to itself.

我有这个 php 函数,它从给定的 PID 中检查脚本的名称,并将其与自身进行比较。

function isRunning($pid) {
    $filename = exec('ps -p '.$pid.' -o "%c"');
    $self = basename($_SERVER['SCRIPT_NAME']);
    return ($filename == $self) ? TRUE : FALSE;
}

From what I know, I usually use this command to get the script name from the PID:

据我所知,我通常使用此命令从 PID 中获取脚本名称:

ps -o PID -o "%c"

It returns me the filename, but only the first 15 characters. Since my script's name is

它返回文件名,但只返回前 15 个字符。由于我的脚本名称是

daily_system_check.php

Daily_system_check.php

the function always returns FALSE, because it's comparing itself with

该函数总是返回 FALSE,因为它正在将自己与

daily_system_ch

Daily_system_ch

Is there another bash command for Centos 6 that will return me script's full name?

Centos 6 是否还有另一个 bash 命令可以返回脚本的全名?

回答by julumme

You didn't specify what is your OS, but in Ubuntu Linux I can see full name of the script with adding --contextto the ps call:

您没有指定您的操作系统是什么,但在 Ubuntu Linux 中,我可以通过添加--context到 ps 调用来查看脚本的全名 :

# ps -p 17165 --context
  PID CONTEXT                  COMMAND
17165 unconfined               /bin/bash ./testing_long_script_name.sh
# 

回答by amc

read the the proc cmdlinefile:

读取proccmdline文件:

cat /proc/$pid/cmdline | awk 'BEGIN {FS="
function isRunning($pid) {
    $filename = basename(exec('ps -o cmd= '.$pid));
    $self = basename($_SERVER['SCRIPT_NAME']);
    return ($filename == $self) ? TRUE : FALSE;
}
"} {print }'

回答by user1105430

There seems to be no flag or collumn in "ps" command to show the whole filename without the filepath or it being cutoff. PHP's basename()gets the job done.

“ps”命令中似乎没有标志或列来显示没有文件路径或被截断的整个文件名。PHP 的basename()完成了工作。

##代码##