简体   繁体   中英

Create multi-process with specified number of childs using fork()

I would like to make a program that has several numbers as input and each number (separated by space) has to be treated in 4 different process to see if it's a prime number. In the case it is, a counter has to be added (so the child must have a shared memory I'm thinking).

Once my process is done with one number, it gets another one that isn't being treated by other process. The idea is for them to work almost in parallel.

What I am thinking of doing is separate the string in tokens and send it to the child process.

Here's what I've done so far:

unsigned int i = 0;
int processes = 4;
char *s=malloc(sizeof(char)*100);

fgets (s, 100, stdin);

for (i = 0; i < processes; ++i) {
    if (fork() == 0) {
        printf("Process %d:", i);
        make_token(s);
        treat_number(token);
        exit(0);
    }
}
// wait all child processes
int status;
for (i = 0; i < processes; ++i)
wait(&status);

return 0;

But with that my program ends after process 4 is done and they aren't exactly working in parallel.

So how can I make it treat several numbers in 4 processes almost at the same time with each getting a different number until my string ends?

An exemple of input/output would be:

Input: 0 10 100000000 100007701 100015739 3 5
Output: 4

Not the most efficient way, but you at least it eliminates the need to communicate with the children:

  • Make all processes know all numbers, perhaps by just letting them know the complete input, as the code already does.
  • Make each process aware which child it is. Currently done by the value of i .
  • Let each process take care of the number-of-processes th number from the input.

    Assuming 4 processes then for i == 3 this would be the 3rd, 7th, 11th ... number from the input, for i == 1 it would be 1st, 5th, 9th, ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM