免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1454 | 回复: 0
打印 上一主题 下一主题

[Linux] 信号量 互斥 ERANGE [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-06-02 18:19 |只看该作者 |倒序浏览
最近在看信号量的问题,写了一个测试程序,大概是利用信号量对共享内存进行互斥操作。其中sender写数据,receiver读数据。采用的思路都是:P(S),内存操作,V(S)。
sender程序运行暂时没什么问题,但是receiver程序在V(S)时总是出现ERANGE的错误。望高手点拨。

附:
receiver程序如下所示:(sender的信号量与其差不多)
// receiver.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
#include <malloc.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>

const int SIZE = 100;

int main(int argc,char** argv) {
   
   int fd = open(argv[1], O_RDWR, 0666);
   if(fd < 0) {
      perror("open failed");
      return;
   }
   ftruncate(fd,SIZE);
   caddr_t addr = mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
   if(addr <= 0) {
      perror("mmap failed");
      return;
   }

   //semaphores
   int semid;
   if((semid = semget(1000,1,0666|IPC_CREAT))<0)//create or open a semaphores
           {
                   printf("Can't create or open semaphores 1000!\n");
        //return -1;
           }
    semctl(semid,0,SETVAL,1);//set the value:1
        struct sembuf sP,sV;//set the operate of P and V
        sP.sem_num = 0;
        sP.sem_op = -1;
        sP.sem_flg = sP.sem_flg & ~IPC_NOWAIT;

        sV.sem_num = 0;
        sV.sem_op = 1;
        sV.sem_flg = sV.sem_flg & ~IPC_NOWAIT;
   
   char* StringSave = (char*)malloc(SIZE);//must malloc,or segmentation fault will happen!!!
   int temp;
   while(1)
   {
   //printf("test\n");
      if(semop(semid,&sP,1)!=0) //P operation
                  printf("Operation P block!\n");
   
      //read from memory
          if( strcmp(addr,StringSave) )
          {
                  printf("%s",addr+strlen(StringSave));
                  fflush(stdout);
                  strcpy(StringSave,addr);
          }
          if(strlen(addr) >= SIZE-1)
                  break;
          if((temp=semop(semid,&sV,1))!=0) //V operation
                  {
                  printf("\n%d\n",errno);
                  printf("%d\n",temp);
                  printf("Operation V failed!\n");
                  }
  }
  free(StringSave);
  printf("\n");
  munmap(addr,SIZE);
}
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP