Clean-up of threaded server

Johannes Stezenbach yawyi at gmx.de
Wed Apr 11 19:17:43 EDT 2001


Michael Ströder <michael at stroeder.com> wrote:
>David Bolen wrote:
>> 
>> Michael Stroeder <michael at stroeder.com> writes:
>> 
>> > I have two problems:
>> >
>> > 1. The server process does not detach from the console anymore (fork
>> > is used for that). This seems to work without the separate helper
>> > thread.
>> >
>> I'm not sure about (1) (perhaps depending on environment, the other
>> thread has its own reference to file handles that you normally close
>> before detaching, and you could try closing them before starting up
>> the thread?)
>
>It seems that I have some problems with file handles. Hmm, but the
>helper thread does not use file handles at all.

Not so. File handles are shared among threads. You must do the fork
before you create a thread, because in Linux (i.e. glibc 2.x/linuxthreads)
threads are processes which happen to share memory, file descriptors etc.
but build in a normal process hierarchy. Because of this process hierarchy,
the linuxthreads library creates an additional manager thread and all
new threads are direct children of the manager thread. When the
main thread exits, all other threads are terminated by the manager thread.

ps is your friend for examining the process/thread hierarchy.


>Is there a way to determine which and/or how many file handles are
>used by a process/thread?

Linux: lsof, or ls /proc/<pid>/fd/
Filehandlesare shared among all threads of a process, so they will
show up under the PIDs of all threads of the process.


>> > 2. For testing purposes the server process can be started
>> > non-detached. In this case KeyboardInterrupt is catched by the main
>> > thread to shut down the process. This does not work with the helper
>> > thread but works without it.
>> Alternatively, threads can be marked as a "daemon" via the threading
>> module setDaemon method, and those threads are permitted to still be
>> executing when the script exits.
>
>isDaemon() of the helper Thread object returns 0.

So simply call self.setDeamon(1) in your threading.Thread
subclass.


HTH,
Johannes




More information about the Python-list mailing list