Gangmax Blog

An Interesting Bash Hung Issue

This is an issue that confused me several days.

Here is the background: A Java program(A) calls given Python script files one by one, read their output for later usage such as logging. And in each Python script file(B), it may call some other bash script(C).

Now there’s a bash script in which it starts a program as background process like below:

1
2
3
4
5
6
7
8
#! /bin/sh
# c.sh

...

./hello &

...

The “hello” program is a daemon which never stops by itself.

And in a Python script it needs to call the bash file like below:

1
2
3
4
5
6
7
8
9
10
# b1.py
import subprocess

...

return_code = subprocess.call("c.sh", shell=True)
logger.debug("Return code: %s", return_code)

...

When wrapping all of them together, after the Java program finishing executing “b1.py” and being suppose to call another “b2.py”, it hangs. I check the Java code and find it’s hung at below:

1
2
3
4
5
while ((len = iStream.read(buffer)) != -1) {
if (os != null) {
os.write(buffer, 0, len);
}
}

So it seems the Java program is waiting for “b1.py” to end it’s out/err streams. However, if the script starts a background process like “hello &”, it hangs.

Somebody told me to change the bash file like below:

1
./hello 2>1>/dev/null &

It doesn’t work and from here I know the grammar is not right, so I tried this but still didn’t work:

1
./hello 2>&1>/dev/null &

Then I tried this, it works:

1
./hello > /dev/null 2>&1 &

However the following one is NOT working:

1
./hello 2>&1 >/dev/null &

Here is an article to explain what “>/dev/null 2>&1” is, but I’m still not very sure what’s the difference between the last two.

Comments