Unexpected Output Running Semaphore [duplicate]

2019-08-30 01:34发布

问题:

This question is an exact duplicate of:

  • Unexpected Output Running Semaphore 1 answer

The first process shouldn't start its (i)th iteration unless the second process has finished its (i-1)th iteration.The output is not what I need.I wonder if it is possible to have the output by only two semaphores? Here is my code.

#include <stdio.h>   
#include <sys/types.h>
#include <unistd.h>  
#include <stdlib.h>  
#include <errno.h>  
#include <semaphore.h>

sem_t semA, semB,sem,m;

int main(void)
{
 int i;

   pid_t child_a, child_b,pid2,pid3;
    sem_init(&semA, 0, 1);
    sem_init(&semB, 0, 0);
sem_init(&m, 0, 0);

   child_a = fork();
//wait();

   if (child_a == 0) {


  //  int j;

      pid2 =getpid();
      for (i = 0; i < 5; )
      {
    sem_wait(&semA);
//sem_wait(&m);
         printf("child1: %d\n", i);
     i++;
     //printf("pid1: %d\n", pid2);
         //printf("--------------------------\n");
         sleep(3);
//sem_post(&m);

sem_post(&semB);
      }
}    
   else {

   child_b = fork();
//wait();
    if (child_b == 0) {

      pid3 =getpid();
      for (i = 0; i < 5;)
      {
sem_wait(&semB);
//sem_wait(&m);
         printf("child2: %d\n", i);
 i++;
         //printf("pid2: %d\n", pid3);
         //printf("--------------------------\n");
         sleep(5);
//sem_post(&m);
sem_post(&semA);

      }

    } 
    }

    exit(0);
   return 0;
}

the output I expect is:

child1: 0
child2: 0
child1: 1
child2: 1
child1: 2
child2: 2
child1: 3
child2: 3
child1: 4
child2: 4
child1: 5
child2: 5
child1: 6
child2: 6
child1: 7
child2: 7
child1: 8
child2: 8
child1: 9
child2: 9

but I get just one child:

child1: 0

(I'm running UBUNTU 12.10)

回答1:

In order to use semaphores across multiple processes, you have to either use named semaphores or place the semaphores in shared memory.

See linux man page sem_overview(7).

For what you are doing, named semaphores are easier to use than shared memory. The following should work:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/stat.h>

sem_t * semA;
sem_t * semB;
int main(void)
{
  int i;

  pid_t child_a, child_b,pid2,pid3;
  semA = sem_open("/mysema", O_CREAT, S_IRUSR | S_IWUSR, 1);
  semB = sem_open("/mysemb", O_CREAT, S_IRUSR | S_IWUSR, 0);

  child_a = fork();

  if (child_a == 0) {

      pid2 =getpid();
      for (i = 0; i < 5; )
      {
        sem_wait(semA);
        printf("child1: %d\n", i);
        i++;
        sem_post(semB);
        sleep(3);
      }
  }
  else {
    child_b = fork();
    if (child_b == 0) {

      pid3 =getpid();
      for (i = 0; i < 5;)
      {
        sem_wait(semB);
        printf("child2: %d\n", i);
        i++;
        sleep(5);
        sem_post(semA);

      }

    }
  }

  exit(0);
  return 0;
}