Search code examples
coperating-systemfork

fork() in C. I need explanation on this code


So, i have this piece of C code

I can't grasp what the second 'for' segment is about. When does it get terminated abnormally?

Can someone enlighten me on that?

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

  #define N 30

  int main() {
    pid_t pid[N];
    int i;
    int child_status;
    for (i = 0; i < N; i++) {
      pid[i] = fork();
      if (pid[i] == 0) {
        sleep(60 - 2 * i);
        exit(100 + i);
      }
    }
    for (i = 0; i < N; i++) {
      pid_t wpid = waitpid(pid[i], & child_status, 0);
      if (WIFEXITED(child_status)) {
        printf("Child%d terminated with exit status %d\n", wpid, WEXITSTATUS(child_status));
      } else {
        printf("Child%d terminated abnormally\n", wpid);
      }
    }
    return (0);
  }

Solution

  • When child is terminate ,to be able to find with which value the child was terminated (either with exit or with return) i have to pash the second parametre in waitpid() with pointer to an integer.So in that integer on return from the call it will include 2 types of information a) if child was terminated well with return or exit or stoped unexpectedly b)the second type will be having the termination value. If i want to know the information from (a) i need to use the macro WIFEXITED(), if this give me true the (b) emerged from macro WEXITSTATUS().This is a simple example

    #include <stdio.h>
    #include <stdlib.h> /* For exit() */
    #include <unistd.h> /* For fork(), getpid() */
    #include <sys/wait.h> /* For waitpid() */
    void delay() { /* Just delay */
     int i, sum=0;
     for (i = 0; i < 10000000; i++)
     sum += i;
     printf("child (%d) exits...\n", getpid());
     exit(5); /* Child exits with 5 */
    }
    int main() {
     int pid, status;
     pid = fork();
     if (pid == 0) /* child */
     delay();
     printf("parent (%d) waits for child (%d)...\n", getpid(), pid);
     waitpid(pid, &status, 0);
     if (WIFEXITED(status)) /* Terminated OK? */
     printf("child exited normally with value %d\n", WEXITSTATUS(status));
     else
     printf("child was terminated abnormaly.\n");
     return 0;
    }
    

    SOS The macro WEXITSTATUS() return only the 8 least important bits of the value when the child is terminate.So if the child wants to "say" something to his parent through exit/waitpid it must be a number up to 255.