【问题标题】:bus error on sem_wait()sem_wait() 上的总线错误
【发布时间】:2012-12-07 20:18:09
【问题描述】:

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

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`

我做错了什么?

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

【问题讨论】:

  • semaphorecount_sem 是如何声明/定义的?它们应该是sem_t *semaphore; 等...此外,sem_wait() 可以出于EINTR 以外的原因返回 -1,您可能需要检查这些...
  • 这是您对sem_wait() 的唯一呼叫吗?您能否在 do{ }while(); 循环中使用 printf() 某些内容以了解信号是否在第一次迭代时发送?
  • 这是在第一次迭代中,我最初确实有一个 print 语句,是的,它是对 sem_wait() 的唯一调用

标签: c linux semaphore


【解决方案1】:

您的程序中一定有其他地方存在错误。以下工作在这里(不需要 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 编译

【讨论】:

  • 错误不在其他地方,我编辑了上面的问题以反映我是如何确定的
  • 另外,我试过你的代码,得到了Program received signal SIGBUS, Bus error.0x00a20915 in sem_post@@GLIBC_2.1 () from /lib/libpthread.so.0
  • 那么肯定有些库有问题。我在这里安装了gcc version 4.5.0 20100604 [gcc-4_5-branch revision 160292] (SUSE Linux)/libpthread-2.11.2.so/lib/librt-2.11.2.souname -aLinux hurx 2.6.34.10-0.6-desktop #1 SMP PREEMPT 2011-12-13 18:27:38 +0100 x86_64 x86_64 x86_64 GNU/Linux,一切正常。
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 2015-04-09
  • 1970-01-01
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
相关资源
最近更新 更多