Reputation: 832
I need my app to be able to run some methods under a new process, and ideally be able to get a return value from those methods however I have not yet found how I can do this (my C++ knowledge is pretty basic).
So to explain better, let's say I have methods A, A1 and A2. Method A will start executing and at some point it will:
I found that I can use fork()
to run code in a subprocess, however this does not suit my needs because it seems to be creating a copy of the parent process and not just running the specific code I want only in the new process. Here is an excerpt of what I tried, I'm not sure if it can be modified to do what I want it to or if I should use something else completely:
int main(){
std::cout << "START" << std::endl;
test1();
test2();
std::cout << "FINISH" << std::endl;
return 0;
}
void test1(){
pid_t pid = fork();
if (pid == 0){
int i = 0;
for (; i < 5; ++i) {
std::cout << "Test 1 " << std::endl;
}
}
}
void test2(){
pid_t pid = fork();
if (pid == 0){
int i = 0;
for (; i < 5; ++i) {
std::cout << "Test 2 " << std::endl;
}
}
}
This however results in test2()
being executed twice, and FINISH printed 4 times since the parent process is copied to the subprocess.
I am doing this on Linux at the moment, although I'll need to do the same for Windows eventually.
Upvotes: 2
Views: 2829
Reputation: 12175
It sound to me like multi-threading might be the best option for you. This way you share the same memory space and can easily get return values. Look into using OpenMP. I think it is by far the easiest way to multi thread. You can launch tasks for each of the function in a parallel block.
int main(){
std::cout << "START" << std::endl;
int ret1, ret2;
#pragma omp parallel
{
#pragma omp task
ret1 = test1();
#pragma omp task
ret2 = test2();
} //blocks at end of parallel block to wait for tasks to finish
std::cout << "FINISH" << std::endl;
return 0;
}
int test1(){
int i = 0;
for (; i < 5; ++i) {
std::cout << "Test 1 " << std::endl;
}
return 0;
}
int test2(){
int i = 0;
for (; i < 5; ++i) {
std::cout << "Test 2 " << std::endl;
}
return 0;
}
I modified the code in my browser so I can not guarantee it compiles but this is how you can launch functions in parallel and get a return value. I do not think forking is the best way to go about it since you would then need some sort of interprocess communication to get data back. Also OpenMP is probably much more efficient. You could also look into using PThreads which is what I think OpenMP uses on the backed but that is more complicated. Also if you are using C++11 look into using std::async(...) which can spawn threads for functions.
Upvotes: 0
Reputation: 409136
First of all your parent process should wait
for the child processes to exit.
Then your child process should exit
once they're done, or else the functions will return on both the child and parent processes.
Upvotes: 3