D
D
dlinyj2016-02-29 12:21:11
linux
dlinyj, 2016-02-29 12:21:11

bash. How to get the PID of a running process so that it can be killed later?

The task was to write a script that starts several processes in a row. Moreover, one of them is launched in the background, after which the others are launched.
The task is to get the PID of the process being started in the background so that it can then be killed. You just need to complete the first one after performing other processes.
Here I can imagine how to implement this, but there is no such thing in BASH. The task is to make it cross-platform.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Saboteur, 2016-02-29
@dlinyj

variable $$ - current PID
variable $! - PID of the last child process.
echo "$$" > file.pid
For other programs

./run_other_program &
echo $!>other_program.pid

F
fogree, 2021-02-18
@fogree

Bash has the $! , which stores the pid of the last process running in the background.
For example:

#!/bin/bash

# Запускаем дочерний процесс в фоновом режиме
my_app &

# Сохраняем в переменной APP_PID его pid, так как в будущем переменная $! может перезаписываться
APP_PID=$!

# Делаем что-то ещё…# Убиваем процесс
kill $APP_PID

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question