0
votes

I'm trying to write a program where, based on a user input value 'n', I'm going to fork that many processes to run simultaneously. In addition, each child is trying to exec to another file that I've created, that will generate a x sleep time, and a x exit value. Ultimately, when a child dies, the parent needs to print the pid and exit_status. The important part is making sure that children death is x, and not concurrent. So far, there's two things I can't figure out.

  1. Getting my execl to run my sleep.c file (as provided below).
  2. Getting the children to fork and die randomly, not in an orderly fashion, and as a result printing who died, with their generated random exit status.

I have two files, Sleep.c and Ranchild.c.

SLEEP.C

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>

/* Generated random sleep time, and return random exit value */

int main()
{
    /* Calculate A Random Time To Sleep 1 - 10 Seconds*/
    srand(time(NULL));
    int r = (rand() % 10) + 1;

    printf("Sleep Time: %d\n", r);
    sleep(r);

    /* Calculate A Random Exit Value */
    int r2 = (rand() % 30) + 1;
    exit(r2);       
}

RANCHILD.C

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>

int main()
{
    /* Get User Input */
    int i, n;

    printf("Please Enter An Integer!\n");

    /* Test User Input */
    if(!scanf("%d", &n)) {
        printf("Invalid Input!\n");
        return -1;
    }   

    /* Initialize Needed Variables */
    pid_t pid[n];
    int status, exit_status;

    for(i = 0; i < n; i++) {

        if((pid[i] = fork()) < 0) {
            perror("Fork Failed!");
            return -2;
        }

        if(pid[i] == 0) {
            execl("sleep", "sleep", (char *)0);
} else {
    /* Print Child Results */
    if (waitpid(-1, &status, WNOHANG) == 0) {
        if(WIFEXITED(status)) {
            exit_status = WEXITSTATUS(status);
            printf("Exit Status From %d was %d!\n", pid[i], exit_status);
        }
    }   

}       
    }

    exit(0);
}

It never manages to exec to the Sleep file, and a sample of the result is this:

3
Exit Status From 27369 was 0!
Exit Status From 27370 was 0!
Exit Status From 27371 was 0!
Sleep Time: 4
Sleep Time: 4
Sleep Time: 4

Your help is greatly appreciated!!

2
You can't check the value of status until you call wait. I don't see a call to wait. - William Pursell
I added the wait, the result is still 0 =[ Maybe I added it wrong? Regardless of the status, the children are still dying concurrently. - Jake Z
They are dying concurrently because you are probably waiting for them in the "else" where you check on the status. You are going to block on the wait and thus create one child at a time in your loop. - Duck
In the sleep.c code, since the child processes are all likely to be started at the same time (same second), using time() to seed srand() is unlikely to work well. Use getpid() too; that is guaranteed to be unique. You might also play with the sub-second part of the result of one of the sub-second timing functions (clock_gettime() or gettimeofday(), for example). But on a multi-CPU chip, the PID is still unique and the time is not necessarily unique. You have the same problem with the exit statuses, of course; all the children are likely to exit with the same status. - Jonathan Leffler
You'll need a loop around the waitpid() call rather than just an if. And the whole waiting business should be done after you've created all the children, not as you create each one. - Jonathan Leffler

2 Answers

2
votes

Suggest something like this. Jonathan is correct. You need something better to seed rand. The children will run so fast it is highly likely they will all end up with the same sleep times and exit codes.

int ret;

for (i = 0; i < n; i++)
{

    if ((pid[i] = fork()) < 0)
    {
        perror("Fork Failed!");
        return -2;
    }

    if (pid[i] == 0)
    {
        if ((ret = execl("sleep", "sleep", (char *)0)) == -1)
        {
            perror("execl");
            exit(1);
        }
    }
}

for (i = 0; i < n; i++)
{
   if (wait(&status) == -1)
   {
      perror("wait"); exit(1);
   }

   if (WIFEXITED(status))
   {
       exit_status = WEXITSTATUS(status);
       printf("Exit Status From %d was %d!\n", pid[i], exit_status);
   }
}

child/execl program

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <math.h>

/* Generated random sleep time, and return random exit value */

void getRandomNumbers(int *r1, int *r2)
{
    int fd;

    if (((fd = open("/dev/urandom", O_RDONLY))) == -1)
    { perror("open"); exit(1);}

    read(fd, r1, sizeof(int));
    read(fd, r2, sizeof(int));
    close(fd);

    return;
}

int main()
{
    int r1 = 0, r2 = 0;

    getRandomNumbers(&r1, &r2);

    int sleeptime = abs((r1 % 10)) + 1;

    printf("Sleep Time: %d\n", sleeptime);
    sleep(sleeptime);

    int exitcode = abs((r2 % 30)) + 1;

    exit(exitcode);
}
1
votes

sleep.c

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>

/* Generated random sleep time, and return random exit value */
int main(int argc, char **argv)
{
    int seed = time(0);
    if (argc > 1)
        seed = atoi(argv[1]);
    srand(seed);

    int r = (rand() % 10) + 1;
    int r2 = (rand() % 30) + 1;

    printf("%d: Seed: %d; Sleep: %d; Exit %d\n", (int)getpid(), seed, r, r2);

    sleep(r);
    exit(r2);       
}

ranchild.c

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

int main(int argc, char **argv)
{
    int n = 10;
    if (argc > 1)
        n = atoi(argv[1]);
    if (n <= 0)
    {
        fprintf(stderr, "%s: invalid number of processes %d\n", argv[0], n);
        return(1);
    }

    int i;
    pid_t pid[n];
    int t = time(0);
    srand(t);

    printf("Time/seed: %d\n", t);

    for (i = 0; i < n; i++)
    {
        int seed = rand();
        fflush(0);
        if ((pid[i] = fork()) < 0)
        {
            fprintf(stderr, "%s: Fork Failed!\n", argv[0]);
            return -2;
        }
        if (pid[i] == 0)
        {
            const char command[] = "sleep";
            char argument[15];
            snprintf(argument, sizeof(argument), "%d", seed);
            execl(command, command, argument, (char *)0);
            fprintf(stderr, "%d: failed to execute %s\n", (int)getpid(), command);
            return(1);
        }
        printf("Child: %d (%d)\n", pid[i], seed);
    }

    int corpse, status;
    while ((corpse = waitpid(-1, &status, 0)) > 0)
    {
        if (WIFEXITED(status))
            printf("%d: Exit Status From %d was %d!\n",
                   (int)time(0), corpse, WEXITSTATUS(status));
        else
            printf("%d: Exit status from %d was 0x%.4X\n",
                   (int)time(0), corpse, status);
    }

    return(0);
}

Sample output

Time/seed: 1381199552
Child: 66443 (1670130041)
Child: 66444 (116849150)
Child: 66445 (1083610692)
Child: 66446 (1583573884)
Child: 66447 (1361431117)
Child: 66448 (134524634)
Child: 66449 (1802726994)
Child: 66450 (1733296282)
Child: 66451 (894940019)
66443: Seed: 1670130041; Sleep: 1; Exit 13
66452: Seed: 281435745; Sleep: 2; Exit 11
66444: Seed: 116849150; Sleep: 3; Exit 5
66449: Seed: 1802726994; Sleep: 3; Exit 30
66447: Seed: 1361431117; Sleep: 5; Exit 25
66445: Seed: 1083610692; Sleep: 5; Exit 8
66448: Seed: 134524634; Sleep: 5; Exit 23
66451: Seed: 894940019; Sleep: 6; Exit 22
66446: Seed: 1583573884; Sleep: 8; Exit 15
66450: Seed: 1733296282; Sleep: 10; Exit 16
Child: 66452 (281435745)
1381199553: Exit Status From 66443 was 13!
1381199554: Exit Status From 66452 was 11!
1381199555: Exit Status From 66444 was 5!
1381199555: Exit Status From 66449 was 30!
1381199557: Exit Status From 66447 was 25!
1381199557: Exit Status From 66445 was 8!
1381199557: Exit Status From 66448 was 23!
1381199558: Exit Status From 66451 was 22!
1381199560: Exit Status From 66446 was 15!
1381199562: Exit Status From 66450 was 16!