查找正在运行的进程的PID,并存储为数组 [英] Find the PID(s) of running processes and store as an array

查看:203
本文介绍了查找正在运行的进程的PID,并存储为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写bash脚本以查找正在运行的进程的PID,然后发出kill命令.我有部分工作,但是我面临的问题是可能有多个进程在运行.我想对找到的每个PID发出kill命令.

I'm trying to write a bash script to find the PID of a running process then issue a kill command. I have it partially working, but the issue I face is that there may be more than one process running. I want to issue a kill command to each PID found.

我想我需要将每个PID放入一个数组中,但是如何操作却一无所获.

I presume I need to put each PID in to an array but am at a loss as to how to do that.

我到目前为止所拥有的:

What I have so far:

pid=$(ps -fe | grep '[p]rocess' | awk '{print $2}')
if [[ -n $pid ]]; then
    echo $pid
    #kill $pid
else
echo "Does not exist"
fi

这将在一行上返回所有PID,但是我不知道如何将其拆分为一个数组.

What this will do is return all PIDs on a single line, but I can't figure out how to split this in to an array.

推荐答案

这里有一个可能有用的衬里

Here's a little one liner that might help

for pid in `ps -ef | grep your_search_term | awk '{print $2}'` ; do kill $pid ; done

只需将 your_search_term 替换为您要终止的进程名称即可.

Just replace your_search_term with the process name you want to kill.

您也可以将其变成脚本,然后将 your_search_term 交换为 $ 1

You could also make it into a script and swap your_search_term for $1

我想我应该解释一下它是如何工作的.

I suppose I should explain how this works.

反勾号``从其中的表达式收集输出.在这种情况下,它将返回进程名称的pid列表.

The back ticks `` collects the output from the expression inside it. In this case it will return a list of pids for a process name.

使用for循环,我们可以遍历每个pid并终止进程.

Using a for loop we can iterate through each pid and kill the process.

EDIT2 :将kill -9替换为kill

replaced kill -9 with kill

这篇关于查找正在运行的进程的PID,并存储为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆