1

So i just want to create a simple forking program that forks 5 children at the rate of 1 per every half second and then displays the date and time when each fork is complete.. so this is the jist of the code

int count = 1;
while(count <= 5){
    int kid = fork();

    if(kid == -1){
        perror("error in fork");
        exit(0);
    } else if(!kid){
        numbytes = read(sockfd, buf, sizeof(buf)-1);
        buf[numbytes] = '\0';
        printf("%s\n",buf);
    }
    count++;
    usleep(500000); //create per every half second, 500000 = 0.5sec
    close(sockfd);

}


return 0;

}

which I thought should be simple enough, but instead of forking 5 times it doubles after each fork.. so it forks 1 time, then 2, then 4, 8.. etc.

Help?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Jeans
  • 11
  • 1

1 Answers1

3

A fork is generally of this form.

    int pid = fork();

    if( pid == -1 ) { /* error */
        fprintf(stderr, "Error forking: %s", strerror(errno));
        exit(1);
    }
    else if( pid == 0 ) { /* child */
        puts("Child");
        exit(0);
    }

    /* Parent */
    printf("Forked %d\n", pid);

Note that the child has to exit else it will continue executing the rest of the program. Usually you have the child process run a function and exit.

The other part is the main program should wait until all child processes are complete, else you get zombies. Usually a loop calling wait() until there's no more children.

int wpid;
int wstatus;
while( (wpid = wait(&wstatus)) != -1 ) {
    printf("Child %d exited with status %d\n", wpid, wstatus);
}

Put it all together and here's how you fork and wait for 5 child processes.

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>

int main() {
    int max_children = 5;

    for( int i = 0; i < max_children; i++ ) {
        int pid = fork();

        if( pid == -1 ) { /* error */
            fprintf(stderr, "Error forking: %s", strerror(errno));
        }
        else if( pid == 0 ) { /* child */
            puts("Child");
            exit(0);
        }

        /* Parent */
        printf("Forked %d\n", pid);
    }

    int wpid;
    int wstatus;
    while( (wpid = wait(&wstatus)) != -1 ) {
        printf("Child %d exited with status %d\n", wpid, wstatus);
    }
}
Schwern
  • 153,029
  • 25
  • 195
  • 336