0

I need to terminate a process and restart it using the same command used to start it. Have done it using the below commands.

But the problem is the command that I receive is different from the original command that is used to start. Original command is having quotes and the command that I receive is without quotes. So It is not getting started.

I don't know why? can anyone help me in resolving this...

Script below:

processes=$(ps aux | grep $1 -i | grep -v grep | grep -v sh | awk '{print $2}')
cntr=0
for i in $processes; do 
        cmd=$(cat /proc/$i/cmdline | tr '\000' ' ')
        kill $i; 
        cmds[$cntr]=$cmd
        cntr=$cntr+1
done

#Restart the process
echo "Commands: " $cmds
for cmd in $cmds; do 
    echo "Starting..." $cmd
    eval "$cmd"
done

Original command: "/apps/test/bin/" xxxxx

My Command: /apps/test/bin xxxxx

sungtm
  • 547
  • 3
  • 12
Anitha.R
  • 344
  • 2
  • 15

1 Answers1

1

The above code reconstruct the command line by joining the arguments with spaces. This will result in special characters being reparsed again (mostly space, but will also get impacted by wildcards like '*').

As an alternative, consider using the "${array[@]}" construct, which will result in the arrays used directly as argument, no reparsing. This will handle spaces, quoting, etc.

Using bash, the original command line for PID $N, can be reconstructed with:

p=()
while IFS= read -d $'\0' p1 ; do
    p+=("$p1")
done < /proc/$N/cmdline
# Execute, in background sub process
kill ...
"${p[@]}" &

See also Reading null delimited strings through a Bash loop

dash-o
  • 13,723
  • 1
  • 10
  • 37
  • ps -aux is not used for extracting command line arguments. It is for getting the PID. As you said, I am using the /proc/PID/cmdline for arguments. My question is, I am not getting the quotes as in original command for starting the process. Anyway, thanks. – Anitha.R Nov 05 '19 at 10:57
  • 1
    @Anitha.R Oops - I did not read the code carefully. Please ignore the comments about cmdline. You can use the parsing logic, include the execute, to recreate the command line, support special characters, etc. – dash-o Nov 05 '19 at 13:15