#!/bin/bash
gcc -o program program.c
nohup ./program &
sleep 120 #sleep for 2 mins
pid=$(ps -ef | grep program | grep -v grep | cut -d" " -f3,3)
Here we are trying to get PID of a child process in parent process. So I believe, it can be done only if child process runs in background. If process runs in foreground, ps command will execute only after child process is completed and then PID can't be obtained.
sleep is used to avoid cases when child process make take a while to get started.
~Others, Please correct if anything wrong here.
will give 2nd field.
This will work for processes running in foreground.
But it looks like for background processes, there is some space at start of process detail line, so we need to get 3rd field using cut command.(Corrected in earlier post)
If you are getting nothing as output, Please post the output of
./program & # run program in the background
wait # wait for it to finish
PID=$! # get it's process ID (if you have a use for it once the program has finished!)
Or if you only want to sleep for 120 seconds:
./program & # run program in the background
sleep 120 # wait for 120 seconds
PID=$! # get it's process ID
The "wait" will halt script execution until the program completes. Just placing it in the background via the "&" will allow the script to continue. The bash "$!" environemt variable will return the process ID of the last command put in the background. No sleep. No wait. Simply execute in background and capture PID via the $! then proceed with what you need to do with the script.
I realize you first mentioned that in #8. I had been typing up #11 while you submitted that. The sleep was introduced by someone else in #2 where they were attempting to use a ps and grep pipe to get the PID. I don't believe that O/P really wants a sleep in there.
---------- Post updated at 01:51 PM ---------- Previous update was at 12:55 PM ----------
I have another question ( not sure if i had to make a new thread)
Now that i have the PID i want to retrieve information about my process, using the command 'top'.
So far i have
top -b -d 1.0 -p $PID
which returns information while my process is running. When the process stops , top is still running. How can i stop it and proceed with my shell?