Python Forum
How to fork a process, kill the child and not kill the parent? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: How to fork a process, kill the child and not kill the parent? (/thread-2285.html)



How to fork a process, kill the child and not kill the parent? - neXussT - Mar-04-2017

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?


RE: How to fork a process, kill the child and not kill the parent? - micseydel - Mar-04-2017

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?


RE: How to fork a process, kill the child and not kill the parent? - pydsigner - Mar-04-2017

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.


RE: How to fork a process, kill the child and not kill the parent? - neXussT - Mar-04-2017

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/python_multithreading.htm

Thanks again.