0

In shell script I am trying to wait for non-child process. I got reference on how to do it from: WAIT for "any process" to finish

My shell script structure is:

Main.sh

func1(){
return 1
}

func2(){
# Wait for func1 to finish
while kill -0 "$pid_func1"; do
      sleep 0.5
done
}
# Call function 1 in background
func1 &
pid_func1=$!
func2 &

In this case how do I receive the return value of func1 inside function func2?

Community
  • 1
  • 1
user613114
  • 2,731
  • 11
  • 47
  • 73
  • just to clarify, this example is asking 'how to wait for child processes', but the title of your question asks how to get the return value for non-child processes. What is the actual question? If you're asking can I get the return code from non-child processes, then it's not generally available – Anya Shenanigans Jan 04 '13 at 11:27

2 Answers2

2

You generally cannot capture the exit status of non-child processes. You may be able to work something involving logging the exit codes to status files and then reading the values, but otherwise you're not going to be able to capture the values

Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
0

I used anothe shell variable to store the return status in this case and checked value of this shell variable whereever required. Find a sample shell script below to simulate the scenario.

#!/bin/bash

func1(){
retvalue=23 # return value which needs to be returned
status_func1=$retvalue # store this value in shell variable
echo "func1 executing"
return $retvalue
}



func2(){
# Not possible to use wait command for pid of func1 as it is not a child of func2
#wait $pid_func1
#ret_func1=$?

while kill -0 "$pid_func1"; do
      echo "func1 is still executing"
      sleep 0.5
done

echo "func2 executing"

#echo "func1 ret: $ret_func1"
echo "func1 ret: $status_func1"
}

# Main shell script starts here

func1 &
pid_func1=$!

func2 &

Hope its useful for others who are facing the same issue.

user613114
  • 2,731
  • 11
  • 47
  • 73