2

Usually, I use the ps command on Linux to find the pid of the process, then I kill the process using this pid and after that I rerun the process with some specific command for this specific process.

My question is - how can I kill and rerun the process in single command?

Is it possible?

1
  • 1
    Some programs listen to a Hangup signal to reload their config files. You can send a SIGHUP by running kill with the -HUP (or -1) argument: kill -HUP 1234 - en.wikipedia.org/wiki/SIGHUP
    – Johan
    Commented Jan 8, 2019 at 11:15

1 Answer 1

2

You could get the PID and then read the /prc/$pid/cmdline file to see the command used to launch it:

pid=123
com=$(perl -pe 's/\0/ /g' /proc/$pid/cmdline)
kill 123 && "$com"

So you could turn that into a function:

restartPid(){
    pid=$1
    com=$(perl -pe 's/\0/ /g' /proc/"$pid"/cmdline)
    kill 123 && "$com"
}

However, this will not work for more complex cases where a command was run with a specific environment. You could start getting more creating and extend this to also include the environment with something like this:

restartPid(){
  pid=$1
  tempFile=$(mktemp)
  perl -pe 's/\0/\n/g' /proc/"$pid"/environ |
    perl -pe 's/^([^=]+)=(.*)/$1="$2"/' > "$tempFile"
  read -r com args < <(perl -lne '@k=split(/\0/); print "$k[0] ",  join " ", map "\"$_\"", @k[1..$#k]' /proc/"$pid"/cmdline)
    dir=$(readlink -f "/proc/$pid/cwd")    
    kill $pid
    ( . \"$tempFile\"; cd "$dir"; eval $com $args )
}

However this is getting quite complex, as you can see, and I cannot guarantee it will always work. Should be a good start though.

1
  • Might also be worth a cd /proc/"$pid"/cwd to start in the same working directory
    – Torin
    Commented Jan 8, 2019 at 13:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .