I am trying to process a queue of files by spawning multiple processes. I want to spawn two children processes in order to traverse a queue of files. As soon as the process of one file ends, the process should pick the next file in the queue and this should go on till the queue is empty.
I know that the memory is copied from parent process for a spawned child process and I am not able to maintain a single queue in order to keep a track of files processed.
Here’s my implementation:
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <vector>
#include <stdio.h>
#include <sys/mman.h>
#include <queue>
using namespace std;
int main (int argc, char **argv)
{
vector < pid_t > process;
pid_t pid = 0;
queue<string> files;
for (int i = 1; i <= 10; ++i) {
string str = "str" + std::to_string(i);
files.push(str);
}
for (int i = 0; i < 2; i++){
cout << "Prefork child process! " << i<< endl;
pid = fork ();
if (pid == 0)
{
string curr = files.front();
files.pop();
cout << "Hello from the child process! " << i << endl;
cout << "I got : " << curr << endl;
return 0;
}
else {
process.push_back(pid);
cout << "Parent for child "<< i << " with pid: " << pid << endl;
}
}
int status;
while ((pid=waitpid(-1, &status, 0))!=-1) {
cout << "Process terminated: " << pid << endl;
}
return 0;
}
In this, I got str1
as input to both processes, but ideally child 1 should get str1, child2 should get str2 and when the process of str1 is completed by child 1, it should pick str3 and so on till the queue is empty.