c - 意外输出运行信号量

标签 c ubuntu semaphore

<分区>

第一个进程不应该开始它的第 (i) 次迭代,除非第二个进程已经完成它的 (i-1) 次迭代。输出不是我需要的。我想知道是否可以通过以下方式获得输出只有两个信号量? 这是我的代码。

#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;
}

我期望的输出是:

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

但我只有一个 child :

child1: 0

(我正在运行 UBUNTU 12.10)

最佳答案

为了跨多个进程使用信号量,您必须使用命名信号量或将信号量放在共享内存中。

参见 linux 手册页 sem_overview(7) .

对于您正在做的事情,命名信号量比共享内存更易于使用。以下应该有效:

#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;
}

关于c - 意外输出运行信号量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16549718/

相关文章:

bash - 为什么此任务不打开浏览器?

session - 登录主服务器上现有的 Putty session

node.js - 无法使用 npm start 启动 Node 站点

c++ - pthread 和 semaphore 在 osx maverick 10.9 中不适用于我

java - 如何获取java中的所有权限?

GNU LD 可以按内存空间打印内存使用情况,而不是仅按体积百分比打印吗?

c - rename() 在使用 Dev C++ 编译的 C 程序中不起作用

c - linux 信号量,一个进程可以阻塞自己吗?

c - 生成数据通信流图(C程序,profiling)

c - 如何确定 C99 中所需的最大对齐