Should I close after popen??

Donn Cave donn at oz.net
Fri Mar 16 01:13:09 EST 2001


Quoth Andrew Markebo <flognat at flognat.myip.org>:
[ ... re should close file explicitly ...]

| I agree, but I tried with close, but I got the following problems:
|
| Traceback (innermost last):
|   File "<stdin>", line 1, in ?
|   File "/usr/tmp/python-18803PG", line 314, in ?
|     mymain()
|   File "/usr/tmp/python-18803PG", line 304, in mymain
|     keepALive()
|   File "/usr/tmp/python-18803PG", line 259, in keepALive
|     if PingAway():
|   File "/usr/tmp/python-18803PG", line 230, in PingAway
|     fd1.close()
| IOError: [Errno 10] No child processes
|
| The code is:
|
|
|     fd1=os.popen("ping -q -c 3 %s 2> /dev/null" % name1)
|     fd2=os.popen("ping -q -c 3 %s 2> /dev/null" % name2)
|     pid1, res1=os.wait(fd1)
|     out1=fd1.read()
|     pid2, res2=os.wait(fd2)
|     out2=fd2.read()
|     fd1.close()
|     fd2.close()

For a moment there I was awfully confused, since Python won't
even try to run that code, but I see you're running an earlier
version, before 2.0.

os.wait() has nothing to do with files.  Before 2.0, it ignored
its argument(s) altogether, so you could call it with a parameter
without any ill effect, but of course without any good effect either.
Its purpose is to reap the status from a fork's exit.  I see you
have evidently figured that much out, but 1) it's just any fork,
probably the first to exit that hasn't been reaped yet, 2) you
can reap this status only once per fork, and 3) the file object
created by popen() has a special close() method that does this
(man pclose).  Except it doesn't use wait(), but rather waitpid()
specifying its own particular process.

So you snatched the process exit status away from underneath the
pclose(), hence the error.

Files normally (in C Python, anyway) close implicitly when they
go out of scope and no reference to them remains in the system.
There's nothing wrong with an explicit close, though, and in
popen() files it also releases the process slot, which until
then (or until the parent's exit)  will appear as a "zombie".

	Donn Cave, donn at oz.net



More information about the Python-list mailing list