-1

I would like to know if there's some way to get inside the while statement (printf("Death of child: %d with exit code %d\n",i, WEXITSTATUS(status));) the integer i from the child.

I'm getting the output from the execlp (this program has a timeout inside that returns a random number) but I would like to get which is the identification i of each returned response.

int main (int argc, char *argv[])
{
  int i;
  int pid;
  int status;
  int pro= atoi (argv[argc - 1]);
  char programName[] = "./child";

  if (argc < 2 || argc > 2){
    printf("Only one argument is allowed\n"); 
    exit (0);
  }


  for (i = 0; i < pro; i++)  
  { 
    pid = fork();
    if(pid == 0) 
    { 
      printf("Created child %d with pid=%d\n",i, getpid());
      char child[10];
      snprintf(child, 10, "%d", i);
      if (execlp(programName, programName, child, NULL) < 0){
        printf("Error running: %s\n",programName);
      }
      exit(2); 
    }    
  }
  while(wait(&status)>0)
  {
    if ( WIFEXITED(status) ){
      printf("Death of child: %d with timeout %d\n",i, WEXITSTATUS(status));
      if (WEXITSTATUS(status) > 5)
      {
        printf("Time exceeded\n");
      }
    }
  } 
  exit (0);
}

Maybe my approach is not correct. Any tip is welcome. I'm completely new in c.

JosepB
  • 2,205
  • 4
  • 20
  • 40
  • It is possible to reach into the memory of another process, but almost certainly not what you want, and would likely require 100+ lines of code. What are you trying to achieve here? – PiRocks Dec 05 '19 at 08:03
  • Have you considered using threads? – PiRocks Dec 05 '19 at 08:03
  • Does this answer your question? [return value from child process c](https://stackoverflow.com/questions/43554978/return-value-from-child-process-c) – Jaideep Shekhar Dec 05 '19 at 08:06

1 Answers1

2

wait will return the pid of the process that changed. To map that back to i, save all your pids returned from fork into a table and reference back as a lookup.

pid_t table[pro] = {0};
pid_t child=0;

for (i = 0; i < pro; i++)  
  { 
    pid = fork();
    if(pid == 0) 
    { 
      printf("Created child %d with pid=%d\n",i, getpid());
      char child[10];
      snprintf(child, 10, "%d", i);
      if (execlp(programName, programName, child, NULL) < 0){
        printf("Error running: %s\n",programName);
      }
      exit(2); 
    }
    else
    {
      table[i] = pid;
    }    
  }
  while((child=wait(&status)) > 0)
  {
    if ( WIFEXITED(status) ){

      i = -1;
      for (int j = 0; j < pro; j++)
      {
        if (table[j] == child))
        {
          i = j;
          break;
        }
      }

      printf("Death of child: %d with timeout %d\n",i, WEXITSTATUS(status));
selbie
  • 100,020
  • 15
  • 103
  • 173