title: Semaphore and father son process
body: <p>I have this code that creates a process &amp; his son , each one of them will make a " for loop " in his code , which will write in a file from a to z and from A to Z ; with the use of only one semaphore the file created contatins only capital letters from " A " to " Z " and one " a " which means only the father completed his loop while the son managed to run only one time.</p>
  
  <p>With the use of two semaphores i managed to run the code like i wanted it to AaBbCcDdEeFf...Zz </p>
  
  <p>So my question is about the following code( with one semaphore ), why does the son not complete his loop ? </p>
  
  <p>Thank you for your help</p>
  
  <p>Edit : clef = key in the code</p>
  
  <pre><code>#include&lt;sys/types.h&gt;
  #include&lt;sys/ipc.h&gt;
  #include&lt;sys/sem.h&gt;
  #include&lt;unistd.h&gt;
  #include&lt;stdio.h&gt;
  
   main()
  {
                  int pid_P2,clef,sema;
                  char i;
                  ushort tab_sema[1];
                  struct sembuf operation [1];
  
                  FILE *p ;
                  p=fopen("file.txt","w");
                  if (p==NULL)
                  {
                   perror("Error opening file");
                   exit(0);
                  }
  
                  clef=ftok("file.txt",8);
  
                  operation[0].sem_num=0;
                  operation[0].sem_flg=0;
  
                  pid_P2=fork();
  
                  sema=semget(clef,1,IPC_CREAT|0600);
                  if (sema==-1)                {                perror("pb semget");
                                                                 exit(0);                }
  
                  semctl(sema,0,SETVAL,1);
  
                  if (pid_P2==0)
                  {                          /* Son's Code */
                    for (i='a';i&lt;'z'+1;i++) 
                     {
                      operation[0].sem_op=-1;
  
                      semop(sema,operation,1);
  
                      fprintf(p,"%c",i);
  
                      fflush(p); 
                      operation[0].sem_op=+1;               
  
                      semop(sema,operation,1);
  
  
                      }
                      exit(0);
                   }
  
                   else{                /* Father's Code */
  
                   for (i='A';i&lt;'Z'+1;i++) 
                    {
                     operation[0].sem_op=-1;
                     semop(sema,operation,1);
  
                     fprintf(p,"%c",i);
                     fflush(p);
                     operation[0].sem_op=+1;
  
                     semop(sema,operation,1);
  
                    }
  
                    sleep(2);
                    exit(0);
                   }
                  fclose(p);             
  }
  </code></pre>