我正在使用命名信号量编写一个多进程程序,在主进程中我使用以下代码打开信号量
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
答案 0 :(得分: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 -lrt
和gcc semconsumer.c -o semconsumer -lrt