How to make sure the spawned shell script has fully started?

I have the following code snippet which start a Unix command in the background via the SSH session.

        monitorCommand = "nohup " + monitorCommand + " > " + logFile + " &";"Starting TE monitor '{}'", monitorCommand);
        Cli ssh = TE.getNewCli();
        String response = ssh.send(monitorCommand);
        pid = Pid.parse(response, "TE monitor");
        setPid(pid, ssh);
        return pid;

Since spawned remote returns the Unix process id instantly as it is running in the background. However, the process does not start fully before the SSH session is closed. I found that the process was abandoned as I could not find the process manually. If I add sleep for 10 seconds before closing the SSH session, I could find the process survive its launching. The reason for its slow starting maybe due to log directory is mounted to several servers. Since this is library code and works for most process launching, I am wondering whether there is a way to delay the pid returning from the Unix to make sure the process is fully started. For the following statement, could it be "blocked" for a while? :-)

String response = ssh.send(monitorCommand);
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

It might be easier to wrap the monitor command in a separate shell script, then call that script in the foreground.  Pass the monitor script and log file names as parameters:

# Call the monitor script and wait for the logfile to be produced

nohup $monscript > $logfile &

while [ $count -lt 10 ]; do
  if [ -f $logfile ]; then
  sleep 1
if [ $count -eq 10 ]; then
  echo Could not start process
  exit 1
exit 0

Open in new window

Then call this with:
monitorCommand = "/path/to/ " + monitorCommand + " " + logFile;

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Shell Scripting

From novice to tech pro — start learning today.