Question

I'm totally newbie in Unix environment and i faced some problems with plain example from Unix Systems Programming book by Robbins.

It's plain chain of processes and each process prints some info to log file and stderr

#define BUFSIZE 1024
#define CREATE_FLAGS (O_WRONLY | O_CREAT | O_APPEND)
#define CREATE_PERMS (S_IRUSR | S_IWUSR| S_IRGRP | S_IROTH)

int main  (int argc, char *argv[]) {
   char buf[BUFSIZE];
   pid_t childpid = 0;
   int i, n;
   if (argc != 3){       /* check for valid number of command-line arguments */
      fprintf (stderr, "Usage: %s processes filename\n", argv[0]);
      return 1;
   }
                                        /* open the log file before the fork */

   n = atoi(argv[1]);                              /* create a process chain */
   for (i = 1; i < n; i++)
       if (childpid = fork())
          break;
   if (childpid == -1) {
      fprintf(stderr, "Failed to fork");
      return 1;
   }

   auto fd = open(argv[2], CREATE_FLAGS, CREATE_PERMS);
   if (fd < 0) {
      fprintf(stderr,"Failed to open file");
      return 1;
   }

   sprintf(buf, "i:%d process:%ld parent:%ld child:%ld\n", 
           i, (long)getpid(), (long)getppid(), (long)childpid);
   fprintf(stderr, buf);
   write(fd, buf, strlen(buf));
   return 0;
}

It's compiled on Netbeans 7.1 with g++ 4.7 and run command is "${OUTPUT_PATH}" 10 /home/maxim/testlog.log

So the problems are:

  1. When i run or debug project it prints out only 2 or 3 lines of info in both console and file. But if i traverse with "Step Over" through childpid = fork(), it prints info about all 10 processes. Is that some compiler optimization or just my fault?

  2. Even when it prints all lines, the output looks like

    i:2 process:6571 parent:6566 child:6572
    i:3 process:6572 parent:1 child:6573
    i:4 process:6573 parent:6572 child:6574
    ...
    i:9 process:6578 parent:1 child:6579
    i:10 process:6579 parent:6578 child:0
    

    Parent pid values for some processes are 1, which seems to be wrong

Was it helpful?

Solution

  1. If the processes each open the same output file there will be a race condition causing the processes to overwrite each other. That is why it only happens when you run at full speed.

  2. When the parent process ends any children that are still alive are either killed or get a new parent depending on a setting in Linux. In your case they seem to get a new parent. That new parent is process 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top