Unexpected Output Running Semaphore

僤鯓⒐⒋嵵緔 提交于 2019-12-08 06:17:44

问题


I'm trying to write a program that forks another process and stays in sync so that the first process doesn't start its (i)th iteration until the second process has finished its (i-1)th iteration. Is this possible using only two semaphores? This is what I have so far:

#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

回答1:


You may need three semaphores.

sem1 sem2 sem3

Process1:

if(FirstRun){
    Initialize the semaphores
    wait for sem2
}

post sem1
wait for sem3

Process2:

if(FirstRun){
    Initialize the semaphores
    post sem2
}

wait for sem1
post sem3

Note: In Initialize the semaphores you have to map the semaphores to a shared memory so that it is accessible by both the processes. Also Do Initialize them to some default value say 0, 0, 0.



来源:https://stackoverflow.com/questions/16549939/unexpected-output-running-semaphore

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!