I have two process and a shared memory zone, my workflow is like this. The process A write some data in the shared memory, after that it should wait and send a signal to other process B to start running. The process B should read some data from the shared memory do some stuff write the result, and send a signal to the process A to keep running, after this process B should wait.
Can anyone plese provide an example or a place where I can find how can I stop a process and how can I start running again the process?. I am working in Linux and C++.
I already have semaphores, but the thing that I do not like, it is that one process is stop a bunch of seconds reading all the time from the shared memory, until it detects that it can run. That’s why I was thinkin only in send a signal in the right moment
Update with the solution
I selected the answer of stefan.ciobaca as favourite because is a complete solution that it works and it has a very good explanation. But in all of the other answers there are other interesting options.
Here is a proof-of-concept of how it can be done:
The above program is actually two programs, a consumer and a producer, depending on how you compile it.
You compile the producer by making sure that the PRODUCER_MODE macro is defined:
The consumer is compiled without defining the PRODUCER_MODE macro:
The consumer and producer share some global memory (8 bytes pointed to by data); the producer’s role is to read two 32-bit integers from stdin and write them to the shared memory. The consumer reads integers from the shared memory and computes their sum.
After writing the data to shared memory, the producer signals to the consumer (via SIGUSR1) that it may begin the computation. After the computation is done, the consumer signals to the producer (via SIGUSR1 again) that it may continue.
Both processes stop when the sum is 0.
Currently, each program begins by outputing its pid and reading from stdin the other program’s pid. This should probably 😀 be replaced by something smarter, depending on exactly what you are doing.
Also, in practice, the ‘while (!cancontinue);’-like loops should be replaced by something else :D, like semaphores. At least you should do a small sleep inside each loop. Also, I think you do not truly need shared memory to solve this problem, it should be doable using message-passing techniques.
Here is an example session, showed in parallel:
I hope this helps. (when you run the programs, make sure the file test_concur.c exists (it’s used to establish the shared memory key (ftok function call)))