Home > database >  Save pid number on a file
Save pid number on a file

Time:10-28

I am running my flask application with nohup command on my linux server. I am trying to save PID number as a variable or save just the PID number on output .

For an example , if i run my flask_application with nohup in below command

nohup python /home/app/run_flask.py > /home/temp/run_flask.out 2> /home/temp/run_flask.err &

this will successfully run in the backgroup and i check if my pid running is by

 ps -ef | grep /home/app/run_flask.py

my server will return this

farid  108708      1  0 23:50 pts/0    00:00:00 python /home/app/run_flask.py
farid  112265  83174  0 23:52 pts/0    00:00:00 grep --color=auto /home/app/run_flask.py

PID which i am trying to capture either as a variable or save it to file is 112265 so that i can include this in my shell script to kill process on certain condition . How can i achieve this ?

I have tried using this command and i was able to print out 112265 , however i am not sure i cant store this as variable by adding 'test1=ps ef....' and if this is the right approach . command used

ps -ef | grep /home/app/run_flask.py | tr -s ' ' | cut -d ' ' -f2 | tail -1

CodePudding user response:

You can do i it like that

VAR=$(ps -ef | grep something_u_want | grep -v grep | awk '{print $2}')

Then VAR will store the number.

By the way are you sure u want to store PID 112265? This is your user search pid which you should exclude using 'grep -v grep'.

CodePudding user response:

You can capture the PID of your command immediately after running the nohup command and store to a variable.

nohup python /home/app/run_flask.py > /home/temp/run_flask.out 2> /home/temp/run_flask.err &
var=$!

Or to save to a file

nohup python /home/app/run_flask.py > /home/temp/run_flask.out 2> /home/temp/run_flask.err &
echo $! > saved_pid.txt
  • Related