multiTasking using fork

i'm very new to UNIX C programming.
I want to replace a very slow forloop in my program so that my tasks be run parallely:

vector <string>inputs;
...populate inputs with 12 strings
for (int i=0;i<12;i++)
process(inputs[i]); //process sends a request to remote network;takes up a lot of time;

I need to write a program that would start 12 parallel calls to the function process, but am having hard time figuring out how to use fork for this. using forloop with fork turned out to be a nightmare!

can anyone point me to useful sample code?
thank you so much! :confused:

You could use threads for this, but I never have, so someone else would have to help you there.

Heres how you could use fork in the for loop:

int pids[12]; // declare this with your inputs array

for(i=0;i<12;i++) {
   pids=fork();
   if(pids==-1) {
      //do whatever you want here -  your fork has failed
   }
   if(pids=0) {
      process(inputs);
   }
}

And you should have a signal handler that is called when any of the children exit.

You may be creating more problems with this solution, than you are solving. I assume it is a working piece of code, albeit slow. Introducing new faults, or even breaking it entirely would be a big NO, NO!

Excercise caution with your approach and test the results from the old code against the new code to highlight any discrepancies.

Also, just an idea, but rather than going complicated, go simple. Use the code you have to accept input for only one request. Allow your (single argument) process to be called as many times as necessary from the OS i.e. the shell. This way you let the OS worry about forking, multi-tasking and such. As I have said, just an idea.

Hope this helps

MBB

Depending on what you need, its best to use thread ...

pthread_t  mythreads[12];
for (int i=0;i<12;i++) 
   pthread_create(mythreads+i, NULL, process, inputs+i);

But then, be warned that more problem will occuer when dealing with threads and really hard as a he** to debug :mad:

Online man page is always the right direction to look for ...

Good luck