Chinaunix

标题: 信号量 互斥 ERANGE [打印本页]

作者: tcjsea    时间: 2013-06-02 18:19
标题: 信号量 互斥 ERANGE
最近在看信号量的问题,写了一个测试程序,大概是利用信号量对共享内存进行互斥操作。其中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);
}





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2