1

我正在使用命名信号量编写一个多进程程序,在主进程中我使用以下代码打开信号量

semaphore = sem_open("/msema",O_RDWR|O_CREAT|O_TRUNC,00777,1);      
if (semaphore == SEM_FAILED)
    perror("SEMAPHORE");

在子程序中

count_sem=sem_open("/msema",O_RDWR);
if(count_sem==SEM_FAILED) 
 {
 perror("sem_open");
 return 1;
 }

在 sem_wait()

   do {
   errno=0;  
printf("BeforeSemWait\n");  
    rtn=sem_wait(count_sem);
printf("afterSemWait\n");
  } while(errno==EINTR);
  if(rtn < 0) {
  printf("Error\n");
  perror("sem_wait()");
  sem_close(count_sem);
  return 1;
 }

我收到来自 sem_wait() 的总线错误

 BeforeSemWait

 Program received signal SIGBUS, Bus error.
 0x00a206c9 in sem_wait@@GLIBC_2.1 () from /lib/libpthread.so.0`

我究竟做错了什么?

编辑:整个代码:master.c:http : //pastebin.com/3MnMjUUM worker.c http://pastebin.com/rW5qYFqg

4

1 回答 1

0

您的程序中一定有其他地方存在错误。以下工作在这里(不需要O_TRUNC):
semproducer.c:

#include <fcntl.h>
#include <stdio.h>
#include <semaphore.h>
int main () {
  sem_t *sem=sem_open("/msema",O_RDWR|O_CREAT /* |O_TRUNC*/ ,00777,1);
  if (sem==SEM_FAILED) {
    perror("sem_open");
  }
  else {
    while (1) {
      sem_post (sem);
      printf ("sem_post done\n");
      sleep (5);
    }
  }
}

semconsumer.c:

#include <fcntl.h>
#include <stdio.h>
#include <semaphore.h>
#include <errno.h>
int main () {
  sem_t *count_sem=sem_open("/msema",O_RDWR);
  if(count_sem==SEM_FAILED) {
    perror("sem_open");
    return 1;
  }
  do {
    int rtn;
    do {
      errno=0;
      rtn=sem_wait(count_sem);
    } while(errno==EINTR);
    if(rtn < 0) {
      perror("sem_wait()");
      sem_close(count_sem);
      return 1;
    }
    printf ("sema signalled\n");
  } while (1);
}

编译gcc semproducer.c -o semproducer -lrtgcc semconsumer.c -o semconsumer -lrt

于 2012-12-08T05:29:00.347 回答