Get current pid linux

Shell script to get the process ID on Linux [duplicate]

I want to write a shell script ( .sh file) to get a given process id. What I’m trying to do here is once I get the process ID, I want to kill that process. I’m running on Ubuntu (Linux). I was able to do it with a command like

@Konstantin imagine you want to kill a Java process. You might have several java processes running and this way you cannot use «killall java» as you would kill every process

To expand on @IgnacioVazquez-Abrams’ comment, unless you know the process doesn’t have a signal handler and/or is broken and doesn’t respect regular kill , this is a useless use of kill -9

9 Answers 9

Using grep on the results of ps is a bad idea in a script, since some proportion of the time it will also match the grep process you’ve just invoked. The command pgrep avoids this problem, so if you need to know the process ID, that’s a better option. (Note that, of course, there may be many processes matched.)

However, in your example, you could just use the similar command pkill to kill all matching processes:

Incidentally, you should be aware that using -9 is overkill (ho ho) in almost every case — there’s some useful advice about that in the text of the «Useless Use of kill -9 form letter «:

  1. shut down socket connections
  2. clean up temp files
  3. inform its children that it is going away
  4. reset its terminal characteristics

@SSHThis: what operating systems / distribution and version are you using? (pgrep / pkill are distributed in procps on Linux-based systems.)

I am on AIX, I basically had just pass the process id as an argument to my script and find it prior to running it. Not a big deal for my case, thanks for the extra info tho 🙂

The meaning of 15 , 2 , 1 signals should be included — or at least a link to read about them: linux.org/threads/kill-signals-and-commands-revised.8096

If you are going to use ps and grep then you should do it this way:

Those square brackets will cause grep to skip the line for the grep command itself. So to use this in a script do:

output=`ps aux|grep r\[u\]by` set -- $output pid=$2 kill $pid sleep 2 kill -9 $pid >/dev/null 2>&1 

The backticks allow you to capture the output of a comand in a shell variable. The set — parses the ps output into words, and $2 is the second word on the line which happens to be the pid. Then you send a TERM signal, wait a couple of seconds for ruby to to shut itself down, then kill it mercilessly if it still exists, but throw away any output because most of the time kill -9 will complain that the process is already dead.

I know that I have used this without the backslashes before the square brackets but just now I checked it on Ubuntu 12 and it seems to require them. This probably has something to do with bash’s many options and the default config on different Linux distros. Hopefully the [ and ] will work anywhere but I no longer have access to the servers where I know that it worked without backslash so I cannot be sure.

Читайте также:  Linux где хранятся удаленные файлы

One comment suggests grep-v and that is what I used to do, but then when I learned of the [] variant, I decided it was better to spawn one fewer process in the pipeline.

Источник

How to Find the PID and PPID of a Process in Linux

Knowing the PID and PPID of a process can be helpful if you need to manage or interact with a process running on your system.

There are numerous ways to get the PID (Process ID) and PPID (Parent Process ID) of a given process in Linux.

Command Description
pidof process_name Works with exact process name
pgrep process_name Returns PID of all matches
ps -o ppid= -p PID Get the PPID from PID
$$ PID of current process/shell
$ PID of current process’s parent

I’ll explain these commands in detail but before that a quick recap of process, PID and PPID.

Linux process basics

Everything that runs on your system is ran via something known as a process, with that simply being the running instance of a program.

All the processes that run on your system are assigned identifiers. These can be helpful if you want to monitor the process (for example, such as to see how much memory or CPU it is using), or maybe if you want to end it if it starts to hang or just act a bit funky.

The identifiers that get attached to all these processes are known as PIDs and PPIDs.

What is a PID?

PID stands for «process ID». Again, this is simply the identifier that gets attached to a program when it starts running, and can be helpful if you need to interact with the process in one way or another.

What is a PPID?

PPID is quite closely related to a PID. PPID stands for «parent process ID», and if you didn’t get it already, it simply stands for the process that created the process you are checking.

For example, let’s say that we have two processes. One is named «spawner», and has a process ID (or PID) of 7234. Our second process, «email client», has a process ID of 7456 when we create it. Our spawner program starts our email client, resulting in our email client having a PID of 7456, and a PPID of 7234, since the spawner (which had the PID of 7234) is what spawned the email client.

Now that you have brushed up your basic, let’s see how to get the process ID in Linux.

Getting the PID of a process

The important thing here is to know the name of the process whose PID you want to find.

If you know the exact process name, you can get its process ID using the pidof command:

Easier said than done because you may not always know the exact process name. Good thing here is that pidof command works with tab completion so if you know the starting few letters of the process name, you can hit tab to get matching suggestions.

Example of pidof command which is used for finding PID of a process in Linux

However, that may not always work if the process name doesn’t match to what you think it is called. For example, the process for Edge browser on Linux is called msedge . It doesn’t start with ‘edge’ and the tab completion won’t work if you focus on ‘edge’.

So, what you can do is to resort to the ps command in Linux to list all the running processes from all users and then use grep on the output to filter the result.

ps aux | grep -i partial_process_name

There is a dedicated command that combines the features ps and grep command and it is unsurprisingly called pgrep:

pgrep partial_or_exact_process_name

pgrep command

The default output shows only the PIDs without any information on the process. This could be troublesome if there is more than one process IDs returned for your searched term.

Hence, I suggest using the listing feature to make sure that you are getting the PID of the desired process.

pgrep -l partial_or_exact_process_name

pgrep command example

You may also use the top command to get the process information but it cannot be used in scripts.

You can use the pstree command to get the PIDs of all running process on your Linux system: pstree -p -a

Getting PPID from a child process’s PID

Once you know the PID of a process, it is effortless to find the PPID for that process.

You can simply run the following command, replacing PID with the current process (child) ID:

In a shell, the above command and $ should both return the same output:

And that’s about everything there is to finding PIDs and PPIDs!

Checking the PID and PPID of the currently running process

If you’re in a shell such as Bash, it’s extremely easy to find the PID and PPID of the calling process (which will usually be the shell).

Bash stores the PID’s value under the $$ variable, and the PPID under the $ variable:

PID and PPID of current shell

And it’s that easy! Finding the PIDs and PPIDs of other processes isn’t much harder either.

Wrapping up

You should now know everything you need to find both PIDs and PPIDs for running processes on your system.

If you need any help getting something working, or just got some remaining questions, feel free to leave that and anything else in the comments below.

Источник

How to find the Process ID (PID) of a running terminal program?

I am running a program in the terminal that I can’t escape with Ctrl — C and that I want to kill. How can I find its PID?

This is a branch of What should I do when Ubuntu freezes? as a reference to prevent details in that question from becoming too technical.

11 Answers 11

Open another terminal and run ps ax | grep foo where foo is the name of the unresponsive program. This should return a line of output that looks something like this:

$ ps ax | grep firefox 2222 ? S 0:00 /bin/sh /usr/lib/firefox-3.6.9/firefox 2231 ? Sl 514:36 /usr/lib/firefox-3.6.9/firefox-bin 30290 pts/2 S+ 0:00 grep --color=auto firefox 

The first field of each line of output is a number which represents the Process ID of the program matched by grep (you can safely ignore the last one, which represents grep itself.

To halt the offending process, do: kill pid where pid is the Process ID of the program. You might have to use your judgment as to which of the matches needs to be kill ed, or you could use top instead. Using kill by itself sends SIGTERM, which you should try first as it allows the program to properly clean up after itself. If SIGTERM fails, try SIGHUP, which is stonger medicine: kill -HUP pid . If all else fails, send SIGKILL. But, you should only do so as a last resort, because SIGKILL causes the kernel to terminate the process immediately with no possibility for cleanup. This can at times result in data corruption or other problems. So again, only send SIGKILL as a last resort. To do so, do kill -KILL pid or kill -9 pid .

If you are running a graphical interface, of course, you don’t have to fool with this crazy command-line stuff to get the job done. Just open «System Monitor», navigate to the Processes tab, choose the process you want to halt (Hm, could it be the one using 90% CPU?) and right-click it. Since the process is already stopped, (that’s the problem, right?) choose End Process or Kill Process from the resulting menu.

Источник

How can a Linux/Unix Bash script get its own PID?

I have a script in Bash called Script.sh that needs to know its own PID. In other words, I need to get PID inside Script.sh . Any idea how to do this?

7 Answers 7

The variable $$ contains the PID.

See the [manual][1] for more information, including differences between the two.

  • $$ Expands to the process ID of the shell.
    • In a () subshell, it expands to the process ID of the invoking shell, not the subshell.
    • In a () subshell, it expands to the process ID of the subshell [1]: http://www.gnu.org/software/bash/manual/bashref.html#Bash-Variables

    In addition to the example given in the Advanced Bash Scripting Guide referenced by Jefromi, these examples show how pipes create subshells:

    $ echo $$ $BASHPID | cat - 11656 31528 $ echo $$ $BASHPID 11656 11656 $ echo $$ | while read line; do echo $line $$ $BASHPID; done 11656 11656 31497 $ while read line; do echo $line $$ $BASHPID; done  

    It redirects a string into the loop (or anything that reads stdin ). The string is referred to as a "here string".

    Example: kill -9 $$ will kill the shell instance it is called from.

    kill -9 (with -9 flag) is considered to be harmful and only to be used if it is absolutely necessary).

    It's considered "dangerous" because the process does not get a chance to respond to the signal (and possibly clean up after itself). Doing kill -9 $$ does exactly 1 thing. It kills the current shell process. This is useful if you have done something in the shell session that you do not want written to .bash_history Like: docker run -e PASSWORD=hunter2 ircbot

    You can use the $$ variable.

    If the process is a child process and $BASHPID is not set, it is possible to query the ppid of a created child process of the running process. It might be a bit ugly, but it works. Example:

    sleep 1 & mypid=$(ps -o ppid= -p "$!") 

    Wherever you are (on an interactive command line or in a script), and in the case you do NOT have access to $BASHPID, you can get access to your current shell pid with this :

    where simple quotes are essential to prevent premature string interpretation (so as to be sure the interpretation occurs in the child process, not in the current one). The principle is just to create a child process and ask for its parent pid, that is to say "myself". This code is simpler than ps-based Joakim solution.

    Источник

Оцените статью
Adblock
detector