I am trying to create a program where it performs some task and exits. however, I want to exit from the program if the user enters some string on the terminal.
The way I thought to solve it:
Create a parent process where it is performing the main task. the main task has a loop.
create a child process where it is waiting for an input from the user. if the user inputs the exit string, the child process will update a variable and kills itself. The loop in the parent process will check for the value of the variable, if that value is changed by the child process, it will also exit. If the user doesn’t input the exit string, the parent process will complete the task and kills itself. at this moment I want to kill the child process also.
How can I do that?
Thanks
Thank you for saying what you are actually trying to accomplish here.
You may find it much easier to create a single multithreaded process rather than create two single threaded processes.
Thread #1 does work in a loop and periodically checks a variable
exit_flag. If the variable is set, then it callsexit. If it finishes the work, it callsexit.Thread #2 waits for input from the user. If it gets input, it sets the variable
exit_flag.This way, when you call
exit, both threads will automatically exit. You will either need to use a mutex/semaphore or another kind of synchronization, e.g., if you havelibatomic-ops:Warning about the above code: Setting a global flag only works this way because the main thread only reads the global flag and nothing else. If you need to send more than one word between threads you’ll need some kind of synchronization mechanism, e.g., a mutex, semaphore, or
AO_store_releasepaired withAO_store_acquire.If you use processes instead of threads: Since processes don’t share mutable memory by default, it is not as easy as “updating a variable”. Each process has its own set of private variables. You would need to set up a region of shared memory or communicate some other way (e.g., signal, pipe, socket) which is extra work for you.
Full example
Here is a quick full example. The main thread does “work” that involves counting down from 5. When it reaches 0, it exits and prints a message. The second thread reads user input, when it reads a line starting with
'e'it sets a flag which causes the main thread to exit.The second thread is created as a detached thread only because we do not need to join with it. It does not affect the correctness of this particular program.
If you call
exit, all threads in your program should be terminated, unless there is something wrong with your platform.Note: This example requires
libatomic-opsand assumes you are using POSIX threads.Sample output (user input is in bold):