Shell script not releasing socket on exit

I’ve written a Xojo desktop application to help me edit and process html pages for my website. In order to speed up testing, I’ve added a shell script (MacOS) to run Python’s SimpleHTTPServer, so that I can immediately see the changes to the web pages.

'sh is declared as a property of the window as a shell_sc, a subclass of shell
sh = new shell_sc
sh.Mode=1 'asynchronous
'Start the local server
sh.Execute("cd ~/documents/TestWebsite; python -m SimpleHTTPServer")
'Display results of command
txFldShell.Text = "ErrCode:"+str(sh.ErrorCode)+" PID:"+str(sh.PID)+EndOfLine

I subclassed the shell so that I can use the DataAvailable event to read back any output from the shell.

It all works great, except that when I shut it down, it doesn’t close the socket. So, when I try to start it again, I get an error message that the socket is in use.

socket.error: [Errno 48] Address already in use

This happens even if I completely shut down both the application and the web browser (Firefox) and then restart them.
This is my shell shutdown code:

'Stop the local server
sh.Close

The only way I’ve found to force the socket to be released is to open the web browser and force it to reload the page. At that point, I get a server not found error on the browser, and it then releases the socket. Then I’m able to restart the server.

When I use the Activity monitor to check what’s running, I see that when I run the shell script to launch the web server, there are actually two processes launched. The first is Bash with the same PID that is returned by my shell code sh.PID. The second process is Python (with a different PID number). It appears that The Python process continues to run after the shell is closed. I’ve tried sending a Ctrl-Z to the shell before closing it, but it doesn’t appear to do anything.

Any ideas on what I can do stop the Python process and to ensure that the socket is released when the shell script exits?

Well, I learn something new everyday. I had assumed that when a parent process quits then the operating system would kill all of its child processes. But no. When the shell is closed the Python program continues to run. And when the Xojo app quits, the processes that had been spawned by the shell script still continue to run. So it’s necessary for the Xojo app to kill all of its spawn. I change the server stop code to this:

'Stop the local server
sh.close 'Need to do this after being in mode 1
sh.Mode=0
'Get PID of python SimpleHTTPServer if it's running
sh.Execute("pgrep -f python\ -m\ SimpleHTTPServer")
dim serverPID As String = trim(sh.Result)
if serverPID<>"" then
  TxtFieldShell.AppendText "Terminating Process: "+serverPID+EndOfLine
  sh.Execute("kill "+serverPID)
end if

That fixed the problem.