Reputation: 3875
I am working on a game, so at one point I had to use fork()
, the main thread runs opengl graphics, and the child thread runs the game logic.
Now I have a problem. At some point, the user may press the 'Exit' button inside the game, which is handled by the secondary thread. Also, at some point the user may click the X button to exit the game which is handled by the main (glut) thread. So here is my question: how can I kill the other running thread, and exit?
Right now, if I close the window, the second thread keeps running, and if the second thread finishes, the first one keeps running.
Handling the 'X' button could be done using the atexit
function, but I haven't found a (safe) way of killing glutMainLoop()
.
Upvotes: 2
Views: 6752
Reputation: 116878
If you are actually calling fork()
(instead of starting a new thread) then you are actually creating another running process. When fork()
is called, it returns a process-id to the parent process. That can be passed to kill()
to kill the process. Under linux this looks like:
#include <signal.h>
pid_t pid = fork();
if (pid == 0) {
// you are in the child process
} else if (pid > 0) {
// you are in the parent process
...
// send a termination signal
kill(pid, SIGTERM);
} else {
// fork had an error which should be logged...
}
You need to choose what signal to send the process. SIGKILL (9) kills it hard for example.
Upvotes: 3
Reputation: 35059
Please be precise about thread
and process
as they describe different subjects.
Since you use fork()
you are actually dealing with processes. I recommend that you use threads
instead, since it is much more memory efficient (since the program needs to be in memory only one time) and easier to handle. Of course you have to deal with critical sections yourself.
Here is a good example for working with threads.
If you insist on using processes and fork()
you can still send signals and implement specific signal handlers. I'd also read some articles about IPC (Inter Process Communication) like http://tldp.org/LDP/lpg/node7.html.
Upvotes: 0