bash shell命令查找进程ID并附加到它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2833355/
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-17 22:06:06  来源:igfitidea点击:

shell command to find a process id and attach to it?

bashdomain-driven-designgrep

提问by Elias Bachaalany

I want to attach to a running process using 'ddd', what I manually do is:

我想使用“ddd”附加到正在运行的进程,我手动执行的是:

# ps -ax | grep PROCESS_NAME

Then I get a list and the pid, then I type:

然后我得到一个列表和 pid,然后我输入:

# ddd PROCESS_NAME THE_PID

Is there is a way to type just one command directly?

有没有办法直接输入一个命令?

Remark: When I type ps -ax | grep PROCESS_NAME, grep will match both the process and grepcommand line itself.

备注:当我输入时ps -ax | grep PROCESS_NAME,grep 将匹配进程和grep命令行本身。

采纳答案by paxdiablo

There is an easy way to get rid of the grep process:

有一种简单的方法可以摆脱 grep 进程:

ps -ax | grep PROCESS_NAME | grep -v ' grep '

(as long as the process you're trying to find doesn't include the string " grep ").

(只要您尝试查找的进程不包含 string " grep ")。

So something like this should work in a script (again, assuming there's only one copy running):

所以这样的事情应该在脚本中工作(同样,假设只有一个副本在运行):

pid=$(ps -ax | grep  | grep -v ' grep ' | awk '{print }')
ddd  ${pid}

If you call your script dddproc, you can call it with:

如果您调用 script dddproc,则可以使用以下命令调用它:

dddproc myprogramname

Although I'd add some sanity checks such as detecting if there's zero or more than one process returned from psand ensuring the user supplies an argument.

尽管我会添加一些健全性检查,例如检测是否有零个或多个进程返回ps并确保用户提供参数。

回答by Paul R

As separate commands:

作为单独的命令:

% PID=`ps -ax | grep ${PROCESS_NAME} | grep -v grep | cut -d ' ' -f 1-2`
% ddd ${PROCESS_NAME} ${PID}

In one line:

在一行中:

% PID=`ps -ax | grep ${PROCESS_NAME} | grep -v grep | cut -d ' ' -f 1-2` && ddd ${PROCESS_NAME} ${PID}

回答by Kiran

Do this way -

这样做——

ddd PROCESS_NAME \`ps -ax | grep PROCESS_NAME | grep -v grep | awk '{print }'\`

回答by Casual Coder

ddd <process_name> `pgrep <process_name>`

回答by anish

you can use pggrep to find the process

您可以使用 pggrep 来查找进程

回答by Randy Proctor

You can use awk to both filter and get the column you want. The "exit" limits the ps results to the first hit.

您可以使用 awk 来过滤并获取所需的列。“退出”将 ps 结果限制为第一次命中。

function ddd_grep() {
  ddd $(ps -ax | awk -v p="" ' == p { print ; exit 0; }');
}

ddd_grep PROCESS_NAME

You may have to adjust the columns for your ps output. Also you can change the ==to ~for regex matching.

您可能需要调整 ps 输出的列。您也可以将==to更改~为正则表达式匹配。