Python Forum

Full Version: How to fork a process, kill the child and not kill the parent?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This post is getting dark.

I have a small gui with tkinter and python 2.7, where I need to execute shutil.copy2(), which can take some time. Obviously, I don't want to block the gui, so I figured I could os.fork() a child process:


pid = os.fork()
if pid == 0:
    shutil.copy2()
    quit() # Kill the child
print "Parent continues..."
That's the general idea. However, what is happening is that when the quit() executes, both child and parent are terminated. Since this is a graphical interface, the mainloop, I expect, would keep the child running if I don't terminate it in some fashion.

I've also tried just creating a new toplevel window for the child, but the copy2() still blocks both the parent and child windows, so that doesn't work either.

How can I kill the child, or am I going about this in the wrong manor?
I'm not super familiar with GUI programming, or forking in Python (I'm surprised actually by what you describe), but why not spawn a thread?
I'd be wary about forking in a GUI application. Like micseydel says, a thread is a much better bet. Just use a callback or something in the thread so that you can notify the GUI when the copy completes.
Hi,

You guys are probably right. fork() is probably best used with console only programs. I'll look into the thread and threading modules and will will post my results for completion of this thread.

Thanks.

Found a very simple drop in that doesn't require any setup.

import thread
import shutil
thread.start_new_thread(copy2, (src, dst))

Running this with a tkinter gui running puts the copy2() function in it's own thread. Seems to exit by itself and does not block the gui. Found examples here:

https://www.tutorialspoint.com/python/py...eading.htm

Thanks again.