fork() in a for loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • daniel fitz
    New Member
    • Nov 2011
    • 1

    fork() in a for loop

    I'm writing a program to stress test the scheduler on a unix distribution. I'm creating a user specified number of processes using fork() and each process should work out prime numbers up to 1000. I'm using a for loop to create the specified number of processes but my program creates too many. I know I need to make sure only the parent forks but i'm just not sure how. Any guidance you could give me would be a massive help. Thanks

    Code:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <string.h>
    #include <sys/wait.h>

    int prime_calc(int prime_range) {
    int prime = 1;
    int i;
    int p;
    for(i = 0; i <= prime_range; i++) {
    for(p = 2; p <= prime_range; p++) {
    if( i != p && i % p == 0) {
    prime = 0;
    break;
    }
    }
    if(prime == 1) {
    printf("Prime: %d\n", i);
    }
    prime = 1;
    }
    return 0;
    }

    int main() {
    int prime_range = 1000;
    int i;
    int pid;
    int pid1;
    for(i = 0; i < 3; i++) {
    pid1 = fork();
    }
    if(pid1==-1) {
    perror("bad fork");
    exit(0);
    }
    if(pid1==0) {
    pid = getpid();
    printf("The process id is: %d\n", pid);
    prime_calc(prim e_range);
    }
    else {
    wait(0);
    }
    return 0;
    }
  • donbock
    Recognized Expert Top Contributor
    • Mar 2008
    • 2427

    #2
    You want a parent process that forks off some number of child processes. Each child process works out the prime numbers up to 1000. You don't say, but I propose that the parent process has nothing else to do after it gets all of the children going.

    This is going to sound like heresy, but I think this is a job for the ignoble goto.

    Code:
    for (i=0; i<nchildren; i++) {
       pid = fork();
       if (pid == 0) goto child_only;
       ...
       }
    ...
    return;
    
    child_only:
    ...
    On another topic, are you certain this will produce the expected load on the operating system? What if the earliest [oldest] children finish their prime number task before the parent finishes forking off their younger siblings?

    Comment

    • johny10151981
      Top Contributor
      • Jan 2010
      • 1059

      #3
      I didn't do much programming using linux and fork,

      But I guess you should not use fork in loop its point less,

      You can call fork once and then call your prim number counting functions in thread

      Comment

      Working...