예제 #1
0
파일: semc.c 프로젝트: OpenSharp/NDceRpc
/* Open or create a semaphore initializing it as necessary.
 */
static int
semid_get(const char *name, int nsems, int oflags, mode_t mode, int value)
{
	key_t key;
	int max;

	if (nsems > MAX_SEMNUM) {
		ERR(errno = ERANGE, "semid_get");
		return -1;
	}
	if ((key = ftok((char *)name, 1)) == (key_t)-1) {
		ERR(errno, "ftok");
		return -1;
	}

	/* This following loop ensures that we know if the semaphore was created
	 * as opposed to just opened so that it can be initialized properly. We
	 * do this by alternating between oflags 0 and IPC_CREATE|IPC_EXCL until
	 * one succeeds.
	 */ 
	for (max = MAX_TRIES; max; max--) {
		int semid;
		union semun arg;

		if ((oflags & O_EXCL) == 0) {
			if ((semid = semget(key, nsems, 0)) != -1) {
				struct semid_ds buf;

				/* This inner try-loop ensures that the semaphore is initialized before
				 * we return even if the semaphore has been created with semget but not
				 * yet initialized with semctl. See Stevens' UNPv2 p274.
				 */
				arg.buf = &buf;
				for (max = MAX_TRIES; max; max--) {
					if (semctl(semid, 0, IPC_STAT, arg) == -1) {
						ERR(errno, "semctl");
						return -1;
					}
					if (buf.sem_otime != 0) {
						return semid;
					}
					sleep(1);
				}

				ERR(errno = ETIMEDOUT, "semid_get");
				return -1;
			} else if (errno != ENOENT) {
				ERR(errno, "semget");
				return -1;
			}
		}
		if ((semid = semget(key, nsems, IPC_CREAT | IPC_EXCL | (mode & 0777))) != -1) {
			struct sembuf initop;

			if (nsems > 1) {
				unsigned short array[MAX_SEMNUM * sizeof(unsigned short)];
				int i;

				arg.array = array;
				arg.array[0] = 0; /* leave the first one 0 to be set with semop */
				for (i = 1; i < nsems; i++) {
					arg.array[i] = value;
				}
				if (semctl(semid, 0, SETALL, arg) == -1) {
					ERR(errno, "semctl");
					semctl(semid, 0, IPC_RMID);
					return -1;
				}
			} else {
				arg.val = 0;
				if (semctl(semid, 0, SETVAL, arg) == -1) {
					ERR(errno, "semctl");
					semctl(semid, 0, IPC_RMID);
					return -1;
				}
			}
                                 /* increment by value to set sem_otime nonzero */
			initop.sem_num = 0;
			initop.sem_op = value;
			initop.sem_flg = 0;
			if (semop(semid, &initop, 1) == -1) {
				ERR(errno, "semop");
				semctl(semid, 0, IPC_RMID);
				return -1;
			}

			return semid;
		} else if ((oflags & O_EXCL) || errno != EEXIST) {
			ERR(errno, "semget");
			return -1;
		}
	}

	ERR(errno = ETIMEDOUT, "semid_get");
	return -1;
}
예제 #2
0
int CSemaphore::CounterInc(int nBCounterSeq )
{
    if (m_nSemID == 0 )
    {
        snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d]", __func__, CACHE_SEM_ERR_COUNTERINC_NOINIT);
        return CACHE_SEM_ERR_COUNTERINC_NOINIT;
    }

    int nRet = -1;
    for(int i = 0; i < m_nSCounterNum; ++i)
    {
        struct sembuf sops[2];
        sops[0].sem_num = GetCounterSWSemSeq(nBCounterSeq)  ;
        sops[0].sem_op = 0;                                     //非0立即返回EAGAIN
        sops[0].sem_flg = IPC_NOWAIT;
        sops[1].sem_num = GetCounterSemSeq(nBCounterSeq);
        sops[1].sem_op = 1;                                     //阻塞+1,超过最大值返回ERANGE
        sops[1].sem_flg = 0;
        
        nRet =  semop(m_nSemID, sops, 2);
        if(nRet < 0 && errno == EINTR)
        {
            snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, SEM_EINTR, strerror(errno));
            return SEM_EINTR;
        }
        
        else if(nRet < 0 && errno == EAGAIN) //开关非0,已经转到下一个SmallCounter
        {
            if(GetSemVal( GetCounterSWSemSeq(nBCounterSeq) ) != 0)//开关非0
            {
                ++ m_nSCounterSeq[nBCounterSeq];
                if(m_nSCounterSeq[nBCounterSeq] >= m_nSCounterNum)
                {
                    m_nSCounterSeq[nBCounterSeq] = 0;
                }
                continue;
            }
            else
            {
                snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d]", __func__, CACHE_SEM_ERR_COUNTERINC_VAL);
                return CACHE_SEM_ERR_COUNTERINC_VAL;
            }
        }
        
        else if(nRet < 0 && errno == ERANGE) //超过最大值,转到下一个index继续
        {
            int save = m_nSCounterSeq[nBCounterSeq];
            
            ++ m_nSCounterSeq[nBCounterSeq];
            if(m_nSCounterSeq[nBCounterSeq] >= m_nSCounterNum)
            {
                m_nSCounterSeq[nBCounterSeq] = 0;
            }
            
            if( GetSemVal( GetCounterSemSeq(nBCounterSeq) ) == 0 )             //下一个SmallCounter计数值为0
                SetSemVal( GetCounterSWSemSeq(nBCounterSeq), 0);               //先开启下一个计数器
            else
            {
                snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d]", __func__, SEM_COUNTER_FULL);
                return SEM_COUNTER_FULL;
            }

            SetSemVal(GetCounterRecSemSeq(nBCounterSeq), m_nSCounterSeq[nBCounterSeq]);            //设置成当正在使用的SmallCounter的index
            
            SetSemVal( 2 * m_nSCounterNum * nBCounterSeq + 2 * save, 1);                            //再关闭这一个计数器

            continue;
        }
        
        else if(nRet < 0)
        {
            
            snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, CACHE_SEM_ERR_COUNTERINC_SEMOP, strerror(errno));
            return CACHE_SEM_ERR_COUNTERINC_SEMOP;
        }
        else
            return 0;
    }

    snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d]", __func__, CACHE_SEM_ERR_COUNTERINC);
    return CACHE_SEM_ERR_COUNTERINC;
}
예제 #3
0
int main(int o_argc, const string const* o_argv) {
  string _path = getExecPath(*o_argv);
  key_t _key = ftok(_path, 'x');
  asserts(_key, "ftok");
  free(_path);
  _path = NULL;

  union  semun  _arg  ;
  struct sembuf _buf  ;
  int           _shmid;
  MyData        _data ;
  size_t        _off  ;
  
  /* Nowaday, memory is so cheap that I just do not care about the unused memory.
   * If is it too waste, then just compile with DYN_SEG_SIZE switch.
  **/
  #ifndef DYN_SEG_SIZE
  const off_t SEG_SIZE = sizeof(mydata_t);
  #endif /* DYN_SEG_SIZE */
  
  _buf.sem_num = 0;
  _buf.sem_flg = 0;

  /* Try to create a set of semaphores. */
  int _semid = semget(_key, 1, IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
  
  if(_semid == -1) {
    const int MAX_TRIES = 6;
    
    /* If semget failed, and the set does not exist then exit */
    if(errno != EEXIST) asserts(_semid, "semget");
    
    _semid = semget(_key, 1, S_IRUSR | S_IWUSR);
    asserts(_semid);
    
    struct semid_ds _ds;
    
    _arg.buf = &_ds;
    
    for(size_t i = 0; i < MAX_TRIES; i++) {
      asserts( semctl(_semid, 0, IPC_STAT, _arg) );
      if(_ds.sem_otime != 0) break;
      sleep(5);
    }
    
    if(_ds.sem_otime == 0)
      fatal (
        "The set of semaphores already exists, but it is not initialized.\n"
        "This is a permanent error, and I have given up."
      )
    ;
  }
  
  /* init semaphore */
  else {
  
    /* Note:
     *   Some systems, like Linux, implicitly initializes a set of semaphores by value 0,
     *   but unfortunately some does not. For that reason, this operation is necessary to ensure
     *   a portability.
    **/
    _arg.val = 0;
    asserts( semctl(_semid, 0, SETVAL, _arg) );
    
    /* post semaphore */
    _buf.sem_op = 1;
    asserts( semop(_semid, &_buf, 1) );
  }
  
  
  /* lock the semaphore */  
  _buf.sem_op = -1;
  asserts( semop(_semid, &_buf, 1) );
  
  /* Critical section: */ 
  
  /* there is no arguments so print shared memory object content */
  if(o_argc == 1) {
  
  
    /* obtain the descriptor of shared memory object */
    asserts( _shmid = shmget(_key, 0, S_IRUSR | S_IWUSR | SHM_RDONLY) );
    
    /* map shared memory object into virtual address space */
    assertv(_data = shmat(_shmid, NULL, 0), cast(void*)-1);

    /* read from shared memory object */
    _off = 0;
    for(size_t i = 0; i < _data->len; i++) {
      print(_data->vals + _off);
      print(" ");
      _off += strlen(_data->vals + _off) + 1;
    }
    
    println("");
  }
  
  /* write arguments in the reveres order into shared memory object */
  else {
  
    #if (defined ALLOW_CLEANUP || defined DYN_SEG_SIZE)
    struct shmid_ds _shmds;
    #endif /* ALLOW_CLEANUP || DYN_SEG_SIZE */
    
    #ifdef ALLOW_CLEANUP
    union semun _semun;
    
    /* if shared memory object already exist obtain its id and destroy, otherwise do nothing */
    if( o_argc == 2 && !strcmp(o_argv[1], "cleanup") ) {
      _shmid = shmget(_key, 0, S_IRUSR | S_IWUSR);  
      if(_shmid == -1) {
        if(errno != ENOENT) asserts(_shmid);
      }
      else asserts( shmctl(_shmid, IPC_RMID, &_shmds) );
      
      /* destroy the semaphore before exit */
      asserts( semctl(_semid, 0, IPC_RMID, _semun) );
      exit(EXIT_SUCCESS);
    } 
    #endif /* ALLOW_CLEANUP */
    
    /* use existing shared memory object or create the new one */
    #ifdef DYN_SEG_SIZE  
    off_t _segSz = sizeof(size_t);
    for(size_t i = 1; i < o_argc; i++) {
      _segSz += strlen(o_argv[i]) + 1;
    }

    /* Try to create a new shared memory object.
     * If such object already exits the destoy it before.
    **/
    _shmid = shmget(_key, _segSz, S_IRUSR | S_IWUSR | IPC_CREAT | IPC_EXCL);
    if(_shmid == -1) {
      if(errno == EEXIST) {
        asserts( _shmid = shmget(_key, 0, S_IRUSR | S_IWUSR) );
        asserts( shmctl(_shmid, IPC_RMID, &_shmds) );
        asserts( _shmid = shmget(_key, _segSz, S_IRUSR | S_IWUSR | IPC_CREAT) );
      }
    }
    #else
    asserts( _shmid = shmget(_key, SEG_SIZE, S_IRUSR | S_IWUSR | IPC_CREAT) );
    #endif /* DYN_SEG_SIZE */

    /* map shared memory object into virtual address space */
    assertv(_data = shmat(_shmid, NULL, 0), cast(void*)-1);
    
    /* write into the shared memory object */
    _data->len = o_argc - 1;
    _off = 0;
    for(size_t i = o_argc - 1; i > 0; i--) {
      /* it is safe to use strcpy, because we got enought memory */
      strcpy(_data->vals + _off, o_argv[i]);
      _off += strlen(o_argv[i]) + 1;
    }
  }
   
  /* unmap shared memory object from virtual address space */
  assertz( shmdt(_data) );
  _data = NULL;
  
  /* unlock the semaphore */
  _buf.sem_op = 1;
  asserts( semop(_semid, &_buf, 1) );

  exit(EXIT_SUCCESS);
}
예제 #4
0
int main(int argc, char *argv[])
{
    int value = 0;

    key_t key = ftok(".", 0xFF);
    int sem_id = semget(key, 1, IPC_CREAT|0644);
    if(-1 == sem_id)
    {
        perror("semget");
        exit(EXIT_FAILURE);
    }

    if(-1 == (semctl(sem_id, 0, SETVAL, value)))
    {
        perror("semctl");
        exit(EXIT_FAILURE);
    }

    //creat the shared memory(1K bytes)
    int shm_id = shmget(key, 1024, IPC_CREAT|0644);
    if(-1 == shm_id)
    {
        perror("shmget");
        exit(EXIT_FAILURE);
    }

    //attach the shm_id to this process
    char *shm_ptr = (char*)shmat(shm_id, NULL, 0);
    if(NULL == shm_ptr)
    {
        perror("shmat");
        exit(EXIT_FAILURE);
    }

    struct sembuf sem_b;
    sem_b.sem_num = 0;      //first sem(index=0)
    sem_b.sem_flg = SEM_UNDO;
    sem_b.sem_op = -1;       //decrease 1,make sem=0
    
    printf("\nMessage receiver is running:\n");
    while(1)
    {
        if(1 == (value = semctl(sem_id, 0, GETVAL)))
        {
            printf("\tThe message is : %s\n", shm_ptr);

            if(-1 == semop(sem_id, &sem_b, 1))
            {
                perror("semop");
                exit(EXIT_FAILURE);
            }
        }

        if(0 == (strcmp(shm_ptr ,"exit")))
        {
            printf("\nExit receiver process now!\n");
            break;
        }
    }

    shmdt(shm_ptr);
    //delete the shared memory
    if(-1 == shmctl(shm_id, IPC_RMID, NULL))
    {
        perror("shmctl");
        exit(EXIT_FAILURE);
    }

    //delete the semaphore
    if(-1 == semctl(sem_id, 0, IPC_RMID))
    {
        perror("semctl");
        exit(EXIT_FAILURE);
    }

    return 0;
}
예제 #5
0
int CSemaphore::CounterInc(int nBCounterSeq )
{
    if (m_nSemID == 0 )
    {
        snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d]", __func__, CACHE_SEM_ERR_COUNTERINC_NOINIT);
        return CACHE_SEM_ERR_COUNTERINC_NOINIT;
    }
    int nRet = 0;
    for(int i = 0; i < 32; ++i)
    {
        struct sembuf sop[1];
        sop[0].sem_num = GetCounterSemSeq(nBCounterSeq)  ;
        sop[0].sem_op = 1;
        sop[0].sem_flg = IPC_NOWAIT;
        
        nRet =  semop(m_nSemID, sop, 1);
        if(nRet >= 0)
        {
            return 0;
        }        
        
        else if(nRet < 0 && errno == EINTR)
        {
            snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, SEM_EINTR, strerror(errno));
            return SEM_EINTR;
        }
        
        else if(nRet < 0 && errno == ERANGE)    //进位
        {
            struct sembuf sops[2];
            sops[0].sem_num = GetCounterSemSeq(nBCounterSeq)  ;
            sops[0].sem_op = - SEM_VALUE_MAX;
            sops[0].sem_flg = IPC_NOWAIT;
            sops[1].sem_num = GetCounterSWSemSeq(nBCounterSeq)  ;
            sops[1].sem_op = 1;
            sops[1].sem_flg = IPC_NOWAIT;
            
            nRet =  semop(m_nSemID, sops, 2);
            if(nRet >= 0)
            {
                return 0;
            }
            
            else if(nRet < 0 && errno == EINTR)
            {
                snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, SEM_EINTR, strerror(errno));
                return SEM_EINTR;
            }
            
            else if(nRet < 0 && errno == EAGAIN)    //低位不够减
            {
                continue;
            }
            
            else if(nRet < 0 && errno == ERANGE)    //高位超过最大值
            {
                snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d]", __func__, SEM_COUNTER_FULL);
                return SEM_COUNTER_FULL;
            }
            
            else
            {
                snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, CACHE_SEM_ERR_COUNTERINC_SEMOP2, strerror(errno));
                return CACHE_SEM_ERR_COUNTERINC_SEMOP2;
            }
        }
        
        else
        {
            snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, CACHE_SEM_ERR_COUNTERINC_SEMOP, strerror(errno));
            return CACHE_SEM_ERR_COUNTERINC_SEMOP;
        }
    }

    snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d]", __func__, CACHE_SEM_ERR_COUNTERINC);
    return CACHE_SEM_ERR_COUNTERINC;
}
예제 #6
0
파일: exo2.c 프로젝트: Chinmay-at-git/M1UPS
int main(int argc, char *argv[]){
    int nb_process; /*nbre  de processus */
    int** pidFils = NULL;
    /*identifiant du semaphore*/
    int semid;
    /*opertaion P et V */
    struct sembuf p;
    struct sembuf v;
    int i, j;

    if(argc != 2){
        printf("Error :\t%s nb_process\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    nb_process = atoi(argv[1]);
    pidFils = malloc(nb_process*sizeof(int));
    for(i=0; i < nb_process; i++){
        pidFils[i] = malloc(sizeof(int));
    }
    /*
     * Nous voulons creer un semaphore, IPC_EXCL ==> si un semaphore existe avec
     *  cet identifiant, la creation echoue
     */
    if((semid = semget(IPC_PRIVATE, nb_process, IPC_CREAT | IPC_EXCL | 0666))
        < 0){
        perror("La creation du semaphore a echoue");
        exit(ERR_SEM);
    }

    printf("############### INITIALISATION #############\n");
    /*initialisation du semaphore,
     0 ==> Numéro de notre sémaphore: le premier
     1 ==> mutex un seul programme a acces a la section critique
     */
    semctl(semid, 0, SETVAL, 1);
    for(i = 1; i < nb_process; i++){
        semctl(semid, i, SETVAL, 1);
    }
    /*initialisation des operations P (blocage) et V (reveil)*/
    p.sem_op = -1; p.sem_flg = 0;
    v.sem_op = 1;  v.sem_flg = 0;
    printf("############### CREATION PROCESSUS #############\n");
    for(i = 1; i < nb_process; i++){
        if(semctl(semid, i, SETVAL, 0) < 0){
            printf("erreur init s %d\n", i);
            exit(7);
        }
    }
    for(i = 0; i < nb_process; i++){
        /* creation des processus */
        if((*pidFils[i] = fork()) == 0){
            j = 0;
            while(j < nb_process*2){
                p.sem_num = i; 
                semop(semid, &p, 1);
                printf("Message Fils num %d pid %d sem %d\n", i, getpid(), 
p.sem_num);
                j++;
                v.sem_num = (i+1)%nb_process;
                semop(semid, &v, 1);
            }
            exit(i);
        }
    }


    /*on attends la fin des processus */
    printf("Le pere attend la mort de ses fils\n") ;
    for(i = 0; i < nb_process; i++){
        wait(0);
    }
    printf("########### FINAL ###########\n");
    if(semctl(semid, i, IPC_RMID, 0) < 0){
        perror("Erreur destruction semaphore");
        exit(ERR_SUPPR);
    }
    printf("Semaphore detruit\n");
    free(pidFils);
    return 0;
}
예제 #7
0
void down(int id) {
        struct sembuf DOWN = {0, -1, 0};
        int semStatus = semop(id, &DOWN, 1);
        exit_on_error(semStatus, "DOWN");
}
int main(int argc, char* argv[]) {
    union semun arg;      /* used to set semaphore parameters */
    struct sembuf sembuf; /* used to do a wait and signal */
    int semID;            /* the shared memory id */
    int flags;            /* flags for semget() call */

    /* check command line args */
    if((argc != 2) || (argv[1][0] != 'p' && argv[1][0] != 'c')) {
        fprintf(stderr, "Usage: a.out {p|c}\n");
        fprintf(stderr, "Where:\n");
        fprintf(stderr, "\tp: Producer (Start second)\n");
        fprintf(stderr, "\tc: Consumer (start first)\n");
        exit(1);
    }

    flags = PERMS|IPC_CREAT;

    /* system calls to create the semaphore */
    semID = semget(KEY, 1, flags);  /* create 1 semaphore in set (index 0) */
    if(semID < 0) {
        perror(">>> ERROR! Consumer must be started first.");
        exit(1);
    }

    if(argv[1][0] != 'p') {
        /* initialize the semaphore */
        arg.val = 0;    /* initalize semphore to 0 */
        if(semctl(semID, 0, SETVAL, arg) < 0) {
            perror (">>> ERROR! Initialization failed.");
            exit(1);
        }
    }

    if(argv[1][0] == 'p') {
        /* Producer does a semsignal() */
        fprintf(stdout, "Producer signaling....\n");
        sembuf.sem_num = 0;     /* first sem in set */
        sembuf.sem_op = 1;      /* 1 means signal */
        sembuf.sem_flg = 0;
        if(semop(semID, &sembuf, 1) == -1) {
            perror(">>> ERROR! Signal failed.");
            exit(1);
        }
    }
    else {
        /* Consumer does a semwait() */
        fprintf(stdout, "Consumer waiting ....\n");
        sembuf.sem_num = 0;     /* first sem in set */
        sembuf.sem_op = -1;     /* -1 means wait */
        sembuf.sem_flg = 0;
        if(semop(semID, &sembuf, 1) == -1) {
            perror(">>> ERROR! Wait failed");
            exit(1);
        }

        fprintf(stdout, "Producer has signaled.\n");

        /* delete */
        if(semctl(semID, 0, IPC_RMID, arg) == -1) {
            perror(">>> ERROR! Unsuccessful delete");
            exit(1);
        }
    }

    fprintf(stdout, "Done.\n");
    return 0;
}
예제 #9
0
int main()
{
        int sockdesc,status;
        struct addrinfo hints;
        struct addrinfo *servinfo;
	/********** Initialization and creation of semaphores for synchronization ********/
	  int shmid,my_sem;
	  union semun arg;
	  struct semid_ds sem_buf;
	  static ushort sem_array[1] = { 1 };
	  struct sembuf up = { 0, 1, 0 };	//Defining the up operation on the semaphore
	  struct sembuf down = { 0, -1, 0 };	//Defining the down operation on the semaphore
	  my_sem = semget (IPC_PRIVATE, 1, 0600);	//Creating the semaphore
	  arg.buf = &sem_buf;
	  arg.array = sem_array;
	  semctl (my_sem, 0, SETALL, arg);	//Setting the value of the semaphore

	shmid = shmget(IPC_PRIVATE, sizeof(int), 0600); //Creating 
	int *counter = (int *) shmat(shmid, 0, 0);
	*counter = 0;

          
        /********** Getting server IP address into structure *************/
        memset(&hints, 0, sizeof(hints));
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_flags = AI_PASSIVE;
        status = getaddrinfo(NULL,"8089",&hints,&servinfo);
        if(status!=0)
        {
                printf("\nError getting address : %s\n",gai_strerror(status));
                exit(1);
        }
        
        /************* Creating a socket ****************/
        sockdesc = socket(servinfo->ai_family,servinfo->ai_socktype,servinfo->ai_protocol);
        if(sockdesc == -1)
        {
                printf("\nError in creating sockets\n");
                exit(1);
        }
        
        /******* Binding the socket to a port **********/
        int binddesc = bind(sockdesc, servinfo->ai_addr, servinfo->ai_addrlen);
        if(binddesc == -1)
        {
                printf("\nError in binding the socket to the port\n");
                exit(1);
        }
        freeaddrinfo(servinfo);
        /********** Listen call **************/
        int listendesc = listen(sockdesc, 10);
        if(listendesc == -1)
        {
                printf("\nError while trying to listen\n");
                exit(1);
        }
        
        /********** Communicating phase **********/
        while(1)
        {
                /*********** Accepting the connections **********/
                struct sockaddr_storage client_addr;
                socklen_t addr_size = sizeof(client_addr);
                int client_sockdesc;
                client_sockdesc = accept(sockdesc, (struct sockaddr*) & client_addr, &addr_size);
		if(!fork())		//child process for handling the requests
		{
			int count,temp;			
			semop (my_sem, &down, 1);                	
	        	*counter = *counter + 1;
			count = *counter;
			semop (my_sem, &up, 1);
			temp=htonl(count);
			int sendflag = send(client_sockdesc, &temp, sizeof(temp), 0);
	                if(sendflag == -1)
        	        {
        	                printf("\nError in sending data\n");
		                exit(1);
        	        }
			exit(0);
		}
                close(client_sockdesc);                     //parent process does not require the connection socket anymore
         }
        close(sockdesc);
}
예제 #10
0
void restore_data(unsigned char *rec_data_package,unsigned int length){ 

	MYSQL *conn;//connect handle(struct st_mysql)
  	my_ulonglong affected_rows;//unsigned __int64
	unsigned char user_id[10] = "";	
	unsigned char current[10] = "";
	unsigned char voltage[10] = "";
    unsigned char zoneId[10] = "";
  	unsigned char query_statement_seg1[] = "INSERT INTO demo VALUES(";//change pointer on .data to array on heap
    unsigned char realtime_statement_seg1[] = "INSERT INTO RealTimeData VALUES(";
    unsigned char voltage_monitor_seg1[] = "INSERT INTO VoltageMonitor VALUES(";
	unsigned char query_statement[200] = "";
	unsigned int id,zoneId_value,current_value,voltage_value;

	/* Shared Memory Related Variable Declaration */
	int ShmID;
	char *ShmPTR;
    
    /* Semaphore Related Variable Declaretion */
	struct sembuf sem_buf = {0,0,SEM_UNDO};
	int sem_id;

	/* 
	** Get The Shared Memory
	*/
    ShmID = shmget(shm_key,100,0666 | IPC_CREAT);
	if(ShmID <= 0){
		perror("Get Shared Memory Id Failed");
		return;
	} else {
		printf("ShmID is : %x\n",ShmID);
	}
    ShmPTR = (char *)shmat(ShmID,NULL,0);//attach a pointer to point at shared memory
    
    /*
	** Get The Semaphore
	*/
	sem_id = semget(sem_key,1,0666 | IPC_CREAT);
	if(sem_id <= 0) {
		perror("Get Semaphore Id Failed!");
		return;
	} else {
		printf("sem_id is : %d\n",sem_id);
	}
	//validation
	if(*(rec_data_package) != startByte || *(rec_data_package + length - 1) != endByte){
        #ifdef DEBUG_TIME
            printf("invalid data:%x\n",rec_data_package[0]);
        #endif

        return;
    }
	//printf("valid data!!\n");
	//printf("%x,%x,%x,%x,%x,%x,%x\n",rec_data_package[0],rec_data_package[1],rec_data_package[2],rec_data_package[3],rec_data_package[4],rec_data_package[5],rec_data_package[6]);
	//reconstruct values
	id = rec_data_package[1];
	current_value = rec_data_package[2] * 256 + rec_data_package[3];
	//printf("current value:%d\n",current_value);
	voltage_value = rec_data_package[4] * 256  + rec_data_package[5];
    
    if(length == 9) zoneId_value = rec_data_package[7];
    else zoneId_value = 1;//default zoneId

	//printf("voltage value:%d\n",voltage_value);
	//*query_statement = "INSERT INTO GPRS_TEST (user_id,current_leak,voltage,rec_time) VALUES('0000','0.000','0.000','2000-01-01-00:00:00')";
	//construct query statement
	
	user_id[0] = 0x30 + id / 100;
	user_id[1] = 0x30 + (id % 100) / 10;
	user_id[2] = 0x30 + id % 10;
	user_id[3] = 0x2C;//comma
	user_id[4] = 0x00;//end of string
    
    zoneId[0] = 0x30 + zoneId_value / 100;
    zoneId[1] = 0x30 + (zoneId_value % 100) / 10;
    zoneId[2] = 0x30 + zoneId_value % 10;
    zoneId[3] = 0x2C;//comma
    zoneId[4] = 0x00;//end of string

	current[0] = 0x30 + (current_value / 10000);
	current[1] = 0x30 + ((current_value % 10000) / 1000);
	current[2] = 0x30 + ((current_value % 1000) / 100);
	//current[3] = 0x30 + (char)(current_value%10);
	current[3] = 0x2C;//comma
	current[4] = 0x00;//end of string

	voltage[0] = 0x30 + (voltage_value / 10000);
	voltage[1] = 0x30 + ((voltage_value % 10000) / 1000);
	voltage[2] = 0x30 + ((voltage_value % 1000) / 100);
	//voltage[4] = 0x30 + (char)(voltage_value%10);
	//voltage[3] = 0x2C;//comma
	voltage[3] = 0x00;//end of string

	//printf("%s\n",rec_data_package);
	//printf("%s\n",query_statement);


	/* DataBase link initialization */
	conn = mysql_init(NULL);
  	/* Connect DataBase */
  	mysql_real_connect(conn,DB_HOST, DB_USERNAME, DB_PASSWORD,DB_NAME, 0, NULL, 0);
	
    if(rec_data_package[6] == 0x01) {
		/* Store History Date */
        strcat(query_statement,query_statement_seg1);//(des,src)
        strcat(query_statement,user_id);
        strcat(query_statement,zoneId);
        strcat(query_statement,current);
        strcat(query_statement,voltage);
        strcat(query_statement,",");
        strcat(query_statement,"current_date,");
        strcat(query_statement,"current_time)");

        #ifdef DEBUG_TIME
            printf("%s\n", query_statement);
        #endif

        mysql_query(conn,query_statement);
    } else if(rec_data_package[6] == 0x50) {
		/* Store Realtime Data */
        strcat(query_statement,realtime_statement_seg1);//(des,src)
        strcat(query_statement,user_id);
        strcat(query_statement,zoneId);
        strcat(query_statement,current);
        strcat(query_statement,voltage);
        strcat(query_statement,")");

        #ifdef DEBUG_TIME
            printf("%s\n", query_statement);
        #endif

        mysql_query(conn,query_statement);
    } else if(rec_data_package[6] == 0x80) {
        /*
        ** Acquire the Semaphore(sem_id,sembuffer,number of sembuffer)
        */
        sem_buf.sem_op = -1;
        if(semop(sem_id,&sem_buf,1) == -1) {
            perror("Can't Acquire Semaphore");
            return 0;
        }
        #ifdef DEBUG_TIME
        perror("start reset shm!");
        #endif
        
        /* Realtime Data Acquire Finished */
        /* index 20 indicate php command sending status */
        *(ShmPTR + 20) = 'f';
        *(ShmPTR + 21) = 'f';
		#ifdef DEBUG_TIME
			printf("reset shared memory!");
		#endif
        
        /*
        ** Release the Semaphore
        */
        sem_buf.sem_op = 1;
        if(semop(sem_id,&sem_buf,1) == -1) {
            perror("Can't Acquire Semaphore");
            return 0;
        }
        #ifdef DEBUG_TIME
        perror("finish reset shm!");
        #endif
    } else if(rec_data_package[6] == 0xa0) {
		/* Store Voltage Monitor Data */
        strcat(query_statement,voltage_monitor_seg1);//(des,src)
        strcat(query_statement,user_id);
        strcat(query_statement,zoneId);
        strcat(query_statement,current);
        strcat(query_statement,voltage);
        strcat(query_statement,",");
        strcat(query_statement,"current_date,");
        strcat(query_statement,"current_time)");

        #ifdef DEBUG_TIME
            printf("%s\n", query_statement);
        #endif
        mysql_query(conn,query_statement);

	} else {
		printf("type is : %x\n",rec_data_package[6]);
	}
  	
	affected_rows = mysql_affected_rows(conn);

  	printf("Affected Row is:%ld\n",(long)affected_rows);

  	if((int)affected_rows < 0)perror("Insert action failed!");

  	mysql_close(conn);//close mysql connection
	
	//return 0;
}
예제 #11
0
파일: ce_sem.c 프로젝트: shajf/cloudeagle
ce_int_t ce_sem_create(ce_sem_t *sem, unsigned int semnum)
{
	int sem_id;
	key_t sem_key;
	union semun arg;
	struct sembuf	initop;
	int save_errno;
	int cnt = 0;
	
	/*get key*/
	sem_key=ftok((const char*)sem->name.data,sem->proj_id);    
	if(-1 == sem_key)
	{
		return CE_ERROR;
	}
	
	sem_id=semget(sem_key, semnum, IPC_CREAT|IPC_EXCL|0666);    
	if(sem_id != -1)
	{
		for (cnt = 0; cnt < semnum; cnt++)
		{
			/*init sem*/
			arg.val=0;
			if(semctl(sem_id,cnt,SETVAL,arg)<0)
			{
				goto err;
			}
			
			initop.sem_num=cnt;
			initop.sem_op=sem->sem_val<=0?1:sem->sem_val;
			initop.sem_flg=0;

			if(semop(sem_id,&initop,1)<0)
			{
				goto err;
			}
		}
		goto fin;
	}	
	else if(errno!=EEXIST)
	{
		
		goto err;
	}
	else //sem existed,then open it
	{
		sem_id=semget(sem_key,0,0);
		goto fin;
	}

	err:
	save_errno=errno;
	if(sem_id!=-1)
	{
		semctl(sem_id,0,IPC_RMID);
	}
	errno=save_errno;
	return CE_ERROR;
	fin:
	sem->sem_id=sem_id;
	return CE_OK;
}
예제 #12
0
/*
** Thread that Sending Data to Client 
**
*/
void *sendDate_handler(void *socket_desc){
    int sock = *(int*)socket_desc;
    int write_status = 0;
	int i = 0;

	/* Message Queue and Semaphore Related Variable Declaration */
	struct msq_buf mybuf;
	int msq_id;
	int data_length;
	int msq_type = 1;

	struct sembuf sem_buf = {0,0,SEM_UNDO};
	int sem_id;
	
	/* Shared Memory Related Variable Declaration */
	int ShmID;
	char *ShmPTR;
	
	/*
	** Get The Semaphore
	*/
	sem_id = semget(sem_key,1,0666 | IPC_CREAT);//if semaphore does't exist , we will create it 
    //but semaphore size is 1 not 3 , so php script can't access it , so we need to run php
    //script first
	if(sem_id <= 0) {
		perror("Get Semaphore Id Failed!");
		return 0;
	} else {
		printf("sem_id is : %d\n",sem_id);
	}
	
	/*
	** Get The Message Queue
	*/
	msq_id = msgget(msq_key,0666 | IPC_CREAT);
	if(msq_id == -1) {
		perror("Get Message Queue Failed!");
		return 0;
	}

	/* 
	** Get The Shared Memory
	*/
    ShmID = shmget(shm_key,100,0666 | IPC_CREAT);
	if(ShmID <= 0){
		perror("Get Shared Memory Id Failed");
		return 0;
	} else {
		printf("ShmID is : %x\n",ShmID);
	}
    ShmPTR = (char *)shmat(ShmID,NULL,0);//attach a pointer to point at shared memory

	while(1) {
        /*
        ** Acquire the Semaphore(sem_id,sembuffer,number of sembuffer)
        */
        sem_buf.sem_op = -1;
        if(semop(sem_id,&sem_buf,1) == -1) {
            perror("Can't Acquire Semaphore");
            return 0;
        }
        /* Start of Restrict Zone */

        /*
        ** Received Message from Message Queue(msq type is 1)
        ** Here , We just fetch 1 message from message queue
        */
        
        data_length = msgrcv(msq_id,&mybuf,MSG_BUFFER_SIZE,msq_type,IPC_NOWAIT);
        mybuf.data[data_length] = '\0';
        
        if(data_length > 0) {
            printf("Received Data is : ");
            for(i = 0; i < data_length;++i){
                printf("%x ",mybuf.data[i]);
            }
            printf("\n");
            #ifdef DEBUG_TIME
            printf("Received Message : %s\n",mybuf.data);
            #endif
            /* index 21 indicate GPRS command sending status */
            if(*(ShmPTR + 21) != 's' && *(ShmPTR + 20) == 's') {
                /* Now,we start query for Data */
                *(ShmPTR + 21) = 's';
                
                write_status = write(sock , mybuf.data, strlen(mybuf.data));
        
            } else {
                #ifdef DEBUG_TIME
                printf("Already Sent Query Command");
                #endif
            }
        }
        /* End of Restrict Zone */
        /*
        ** Release the Semaphore
        */
        sem_buf.sem_op = 1;
        if(semop(sem_id,&sem_buf,1) == -1) {
            perror("Can't Acquire Semaphore");
            return 0;
        }
        
        if(write_status == -1){
            perror("Write Data to Client Failed!");
            return 0;
        }
        usleep(500000);//sleep for 0.5 second
	}

	return 0;
}
예제 #13
0
/*
 * sem_down - down()'s a semaphore
 */
static inline void sem_down(int semid)
{
	if ( semop(semid, SMrdn, 2) == -1 )
		error_exit("semop[SMrdn]");
}
예제 #14
0
/*
 * sem_up - up()'s a semaphore.
 */
static inline void sem_up(int semid)
{
	if ( semop(semid, SMrup, 1) == -1 )
		error_exit("semop[SMrup]");
}
예제 #15
0
파일: syscall_rt.18.c 프로젝트: 8l/rose
void
testaccess_ipc (int ipc_id, char opt, int mode, int expected, char *outbuf)
{
  int actual, semval, rc;
  int myerror = 0;
  char *chPtr;
  struct sembuf sop;
  uid_t tmpuid;
  gid_t tmpgid;
  struct msqbuf
  {
    long mtype;
    char mtext[80];
  } s_message, r_message;

  /* If we are root, we expect to succeed event
   * without explicit permission.
   */
  strcat (outbuf, (expected == -1) ? "expected: fail  " : "expected: pass  ");

  switch (opt)
    {
      /* Shared Memory */
    case 'm':
      /* Try to get (mode) access
       * There is no notion of a write-only shared memory
       * segment. We are testing READ ONLY and READWRITE access.
       */
      chPtr = shmat (ipc_id, NULL, (mode == O_RDONLY) ? SHM_RDONLY : 0);
      if (chPtr != (void *) -1)
{
  strcat (outbuf, "actual: pass ");
  actual = 0;
  if (shmdt (chPtr) == -1)
    {
      perror ("Warning: Could not dettach memory segment");
    }
}
      else
{
  myerror = errno;
  strcat (outbuf, "actual: fail ");
  actual = -1;
}
      break;
      /* Semaphores */
    case 's':
      tmpuid = geteuid ();
      tmpgid = getegid ();
      semval = semctl (ipc_id, 0, GETVAL);
      /* Need semaphore value == 0 to execute read permission test */
      if ((mode == O_RDONLY) && (semval > 0))
{
  setids (0, 0);
  if ((semctl (ipc_id, 0, SETVAL, 0)) == -1)
    {
      printf ("Unable to set semaphore value: %d\n", errno);
    }
  setids (tmpuid, tmpgid);
}
      /* Try to get mode access */
      sop.sem_num = 0;
      sop.sem_op = mode;
      sop.sem_flg = SEM_UNDO;
      actual = semop (ipc_id, &sop, 1);
      myerror = errno;
      if (actual != -1)
{
  strcat (outbuf, "actual: pass ");
  /* back to semaphore original value */
  if (mode != O_RDONLY)
    {
      sop.sem_op = -1;/* decrement semaphore */
      rc = semop (ipc_id, &sop, 1);
    }
}
      else
{
  /* Back to semaphore original value */
  if ((mode == O_RDONLY) && (semval > 0))
    {
      setids (0, 0);
      if ((semctl (ipc_id, 0, SETVAL, semval)) == -1)
{
  printf ("Unable to set semaphore " "value: %d\n", errno);
}
      setids (tmpuid, tmpgid);
    }
  strcat (outbuf, "actual: fail ");
}
      break;
      /* Message Queues */
    case 'q':
      tmpuid = geteuid ();
      tmpgid = getegid ();
      if (mode == O_RDONLY)
{
  setids (0, 0);
  /* Send a message to test msgrcv function */
  s_message.mtype = 1;
  memset (s_message.mtext, '\0', sizeof (s_message.mtext));
  strcpy (s_message.mtext, "First Message\0");
  if ((rc = msgsnd (ipc_id, &s_message,
    strlen (s_message.mtext), 0)) == -1)
    {
      printf ("Error sending first message: %d\n", errno);
    }
  setids (tmpuid, tmpgid);
}
      s_message.mtype = 1;
      memset (s_message.mtext, '\0', sizeof (s_message.mtext));
      strcpy (s_message.mtext, "Write Test\0");

      /* Try to get WRITE access */
      if (mode == O_WRONLY)
{
  actual = msgsnd (ipc_id, &s_message, strlen (s_message.mtext), 0);
}
      else
{
  /* Try to get READ access */
  actual = msgrcv (ipc_id, &r_message,
   sizeof (r_message.mtext), 0, IPC_NOWAIT);
}
      myerror = errno;
      if (actual != -1)
{
  strcat (outbuf, "actual: pass ");
}
      else
{
  strcat (outbuf, "actual: fail ");
}
      if (((mode == O_RDONLY) && (actual == -1)) ||
  ((mode == O_WRONLY) && (actual != -1)))
{
  setids (0, 0);
  /* discard the message send */
  rc = msgrcv (ipc_id, &r_message,
       sizeof (r_message.mtext), 0, IPC_NOWAIT);
  setids (tmpuid, tmpgid);
}
      break;
    }

  if ((actual == expected) || ((expected == 0) && (actual != -1)))
    {
      strcat (outbuf, "\tresult: PASS\n");
      totalpass++;
    }
  else
    {
      errno = myerror;// restore errno from correct error code
      sprintf (&(outbuf[strlen (outbuf)]), "\tresult: FAIL : "
       "errno = %d\n", errno);
      totalfail++;
    }
  printf ("%s", outbuf);
  return;
}
예제 #16
0
int hijo(char clase[5], int max_t, FILE *file )
{
    int x,returnvalue;
    /* Variables de programa */
    int id_shm,id_sem;
    char *sh_mem;
    ushort sem_array[(N_PARTES*3)+2];

    union semun sem_arg;
    struct sembuf *sem_ops=calloc(2,sizeof(struct sembuf));
    
    sem_ops[0].sem_flg=0;
    sem_ops[1].sem_flg=0;

    debug1("%s: Hijo empieza su ejecucion",clase);
    printf("%s: Hijo empieza\n",clase);
    debug3("%s: max_t=%d",clase,max_t);

    debug2("%s: Abro el semaforo",clase);
    id_sem=semget(LLAVE,(N_PARTES*3)+2,0666);
    debug3("%s: id_sem=%d",clase,id_sem);
    sem_arg.array=sem_array;

    debug2("%s: Abro la memoria compartida",clase);
    id_shm=shmget(LLAVE,SHMTAM,0666);
    sh_mem=shmat(id_shm,0,0);


    while (!hayquesalir){
        debug2("%s: Intento conseguir una posicion dentro del sem"
            "aforo de mi clase",clase);
        debug3("%s=> %d tiene sem_value=%d",clase, NSEM_CONS,
            semctl(id_sem,NSEM_PROD,GETVAL));
        sem_ops[0].sem_num=NSEM_PROD;
        sem_ops[0].sem_op=SEM_WAIT;
        sem_ops[0].sem_flg=0;
        semop(id_sem,sem_ops,1);
        semctl(id_sem,0,GETALL,sem_arg);

        debug3("%s: Antes de entrar, hayquesalir=%d",clase,hayquesalir);
        for(x=0;(x<N_PARTES);x++)
            debug3("%s: SHA%1d=%-3u SHA%1dPROD=%-3u SHA%1dCONS=%-3u",
                clase,x,sem_arg.array[x*3],x,sem_arg.array[x*3+SEM_PROD],
                x,sem_arg.array[x*3+SEM_CONS]);

        
        for(x=0;(x<N_PARTES)&&(!hayquesalir);x++){
            debug2("%s: Busco un hueco en el semaforo %d",clase,x);
            if(1==sem_arg.array[x*3]&&1==sem_arg.array[x*3+SEM_PROD]){
                debug2("%s: He encontrado un hueco en la zona %d de la "
                    "memoria compartida. Me quedare hasta que haga"
                    " mi trabajo", clase, x);

                sem_ops[0].sem_num=x*3;
                sem_ops[0].sem_op=SEM_WAIT;
                sem_ops[1].sem_num=x*3+SEM_PROD;
                sem_ops[1].sem_op=SEM_WAIT;
                returnvalue=semop(id_sem,sem_ops,2);
                if(returnvalue==-1){
                    if(EINTR==errno){
                        debug2("%s: Se me ha mandado acabar mientras"
                        " estaba en la cola de espera de %d",clase,x);
                        sem_ops[0].sem_op=SEM_SIGNAL;
                        sem_ops[1].sem_op=SEM_SIGNAL;
                        sem_ops[1].sem_num=NSEM_PROD;
                        exit(EXIT_SUCCESS);
                    }
                    else
                        debug2("%s: Ha devuelto -1... errno a comprobar",
                        clase);
                }
                semctl(id_sem,0,GETALL,sem_arg);
                debug3("%s: SHA%1d=%-3u SHA%1dPROD=%-3u SHA%1dCONS=%-3u",
                    clase,x,sem_arg.array[x*3],x,
                    sem_arg.array[x*3+SEM_PROD],x,
                    sem_arg.array[x*3+SEM_CONS]);

                debug2("%s: He conseguido el acceso a la zona %d",clase,x);

                /*
                 * Aqui hacemos lo que hemos venido a hacer, leemos del 
                 * archivo que se nos dice y escribimos en la memoria
                 * compartida
                 */
                
                debug3("%s: Se han metido %d caracteres en memoria compar"
                    "tida",clase,snprintf(sh_mem+x*3,TAM_PARTES,
                    "soy el productor %s y tengo un mensaje para ti: mi p"
                    "id es %d\n",clase,getpid()));

                debug2("%s: He acabado mis cosas en la zona %d, ahora toc"
                    "a salir",clase,x);
                sem_ops[0].sem_op=x*3;
                sem_ops[0].sem_op=SEM_SIGNAL;
                sem_ops[1].sem_num=x*3+SEM_CONS;//Le abro el camino al cons
                sem_ops[1].sem_op=SEM_SIGNAL;
                semop(id_sem,sem_ops,2);
                debug3("%s: He mandado SEM_SIGNAL al otro y he liberado e"
                    "l acceso a esta zona",clase);
                x=N_PARTES;
            }
        }
        debug2("%s: Como ya he hecho mi trabajo, dejo que otro acceda"
            ,clase);
        sem_ops[0].sem_op=SEM_SIGNAL;
        sem_ops[0].sem_num=NSEM_CONS;
        semop(id_sem,sem_ops,1);
        sleep(1);
    } 
    exit(EXIT_SUCCESS);
}
예제 #17
0
파일: walaxsi.c 프로젝트: Zex/walaxsi
void try_sem()
{
	key_t key;
	int semid, tmp_semid;
	union semun semopt;
	int i;
	struct sembuf sbuf;
	struct semid_ds seminfo;

	get_key('s', &key);

	printf("---------------- semaphore ----------------\n");
	printf("creating semaphore set with key 0x%x\n", key);
	if((semid = semget(key, DEFAULT_SEM_NUM, DEFAULT_FLAGS)) == -1) {
		perror("semget");
		exit(1);
	}
	printf("created semaphore set of id %d\n\n", semid);

	semopt.val = INIT_SEM_VALUE;

	for(i = 0; i < DEFAULT_SEM_NUM; i++) {
		semctl(semid, i, SETVAL, semopt);
	}

//	if((tmp_semid = semget(semid, 0, DEFAULT_FLAGS)) == -1) {
//		perror("semget");
//		semctl(semid, 0, IPC_RMID, 0);
//		exit(1);
//	}
//	printf("%d\n", tmp_semid);

	printf("locking semaphore %d in set %d\n",
		DEFAULT_TEST_SEM, semid);

	sbuf.sem_num = DEFAULT_TEST_SEM;
	sbuf.sem_op = -1;
	sbuf.sem_flg = IPC_NOWAIT;

	//if(semop(semid, &sbuf, SEM_UNDO) == -1) {
	if(semop(semid, &sbuf, 1) == -1) {
		perror("semop");
		semctl(semid, 0, IPC_RMID, 0);
		exit(1);
	}
	printf("locked semaphore %d in set %d\n",
		DEFAULT_TEST_SEM, semid);
	printf("value of semaphore %d: [%d]\n\n",
		DEFAULT_TEST_SEM,
		semctl(semid, DEFAULT_TEST_SEM, GETVAL, 0));

//	print_xsi_info("sem", semid);

	if((semid = semctl(semid, 0, SEM_STAT, &seminfo)) == -1) {
		perror("semctl");
		semctl(semid, 0, IPC_RMID, 0);
		exit(1);
	}

	printf("current permissions %o\n", seminfo.sem_perm.mode);
	printf("changing permissions\n");
	seminfo.sem_perm.mode = 0664;
	semopt.buf = &seminfo;
	semctl(semid, 0, IPC_SET, semopt);
	printf("current permissions %o\n\n", seminfo.sem_perm.mode);

	printf("unlocking semaphore %d in set %d\n",
		DEFAULT_TEST_SEM, semid);

	sbuf.sem_num = DEFAULT_TEST_SEM;
	sbuf.sem_op = 1;
	sbuf.sem_flg = IPC_NOWAIT;

	//if(semop(semid, &sbuf, SEM_UNDO) == -1) {
	if(semop(semid, &sbuf, 1) == -1) {
		perror("semop");
		semctl(semid, 0, IPC_RMID, 0);
		exit(1);
	}
	printf("unlocked semaphore %d in set %d\n",
		DEFAULT_TEST_SEM, semid);
	printf("value of semaphore %d: [%d]\n\n",
		DEFAULT_TEST_SEM,
		semctl(semid, DEFAULT_TEST_SEM, GETVAL, 0));

//	if(semctl(semid, 0, SEM_STAT, &seminfo) == -1) {
//		perror("semctl");
//		semctl(semid, 0, IPC_RMID, 0);
//		exit(1);
//	}

	printf("removing semaphore set %d\n", semid);
	semctl(semid, 0, IPC_RMID, 0);
	printf("removed semaphore set %d\n\n", semid);
}
예제 #18
0
/*
 * Class:     javax_comm_CommPortIdentifier
 * Method:    monitorInterJVMDeviceAccessNC
 * Signature: (Ljava/lang/Thread;)I
 *
 * Currenty not Supported on Posix Devices
 */
int cygCommPortIdentifier_monitorInterJVMDeviceAccessNC
(JNIEnv *jenv, jobject jobj, jobject jtho) {
	int		pollingTime;	/* seconds */
	int		oldVal, newVal;
	jclass		jc;
	jmethodID	jm;
	jfieldID	pnameID;
	jstring		pname;
	const char	*pnamec;
	jboolean	isInterruptedReturn;
	jclass		jcpoc;		/* CommPortOwnershipListener interf */
	jfieldID	cpoPOID;	/* PORT_OWNED ID */
	jfieldID	cpoPUID;	/* PORT_UNOWNED ID */
	jfieldID	cpoPRID;	/* PORT_OWNERSHIP_REQUESTED ID */
	jint		cpoPO;		/* PORT_OWNED value */
	jint		cpoPU;		/* PORT_UNOWNED value */
	jint		cpoPR;		/* PORT_OWNERSHIP_REQUESTED value */
	jmethodID	jintMethod;
	jclass		jthreadClass;
	int		semID;
	union semuni	scarg;
	int		mypid = getpid();
	int		scpid;
	pollingTime = getPollingTime(jenv);
	/* Get the class ID of the CommPortIdentifier object.*/
	jc = (*jenv)->GetObjectClass(jenv, jobj);
	assertexc(jc);
	/* Get the id of the method to report a change-ownership event. */
	jm = (*jenv)->GetMethodID(jenv, jc, "fireOwnershipEvent", "(I)V");
	assertexc(jm);
	/* Get the const values for the CommPortOwnershipListener events.*/
	jcpoc = (*jenv)->FindClass(jenv, "javax/comm/CommPortOwnershipListener");
	assertexc(jcpoc);
	cpoPOID = (*jenv)->GetStaticFieldID(jenv, jcpoc, "PORT_OWNED", "I");
	assertexc(cpoPOID);
	cpoPO = (*jenv)->GetStaticIntField(jenv, jcpoc, cpoPOID);
	cpoPUID = (*jenv)->GetStaticFieldID(jenv, jcpoc, "PORT_UNOWNED", "I");
	assertexc(cpoPUID);
	cpoPU = (*jenv)->GetStaticIntField(jenv, jcpoc, cpoPUID);
	cpoPRID = (*jenv)->GetStaticFieldID(jenv, jcpoc, "PORT_OWNERSHIP_REQUESTED", "I");
	assertexc(cpoPRID);
	cpoPR = (*jenv)->GetStaticIntField(jenv, jcpoc, cpoPRID);
	/* Get the port name. */
	pnameID = (*jenv)->GetFieldID(jenv, jc, "name", "Ljava/lang/String;");
	assertexc(pnameID);
	pname = (*jenv)->GetObjectField(jenv, jobj, pnameID);
	assertexc(pname);
  	pnamec = (*jenv)->GetStringUTFChars(jenv, pname, 0);
	/* Get the corresponding semaphore ID for the port name. */
	semID = GetSemID(pnamec);
  	(*jenv)->ReleaseStringUTFChars(jenv, pname, pnamec);
	if (semID == -1)
		return -1;
	/* Get access to the interrupted method. */
	jthreadClass = (*jenv)->FindClass(jenv, "java/lang/Thread");
	assertexc(jthreadClass);
	jintMethod = (*jenv)->GetMethodID(jenv, jthreadClass, "isInterrupted", "()Z");
	assertexc(jintMethod);
	(void)memset(&scarg, 0, sizeof(scarg));
/* what is this for? */
	/* Get the current value of the semaphore. */
#ifdef  _POSIX_SEMAPHORES
	if ((sem_getvalue(sem_lookup(semID), &oldVal)) < 0) {
#else
	if ((oldVal = semctl(semID, 0, GETVAL, scarg)) < 0) {
#endif		
		(void)fprintf(stderr, "Java_javax_comm_CommPortIdentifier_monitorInterJVMDeviceAccessNC: semctl error %d!\n", errno);
		return -1;
	}
/* !!!!!!!!!!!!!! */
	while(1)
	{
		/* Check to see if this thread has been interrupted. */
		isInterruptedReturn = (*jenv)->CallBooleanMethod(jenv, jtho, jintMethod);
		if(isInterruptedReturn == JNI_TRUE)
			break;
		/* If the semaphore was locked the last time, wait until it
		   gets unlocked.  Else, catch some breath.
		 */
#ifdef NCI
		if (oldVal) {
#ifdef  _POSIX_SEMAPHORES
			if(sem_wait(sem_lookup(semID)) <0){
#else
			if (semop(semID, dev_wait, NOOF_ELEMS(dev_wait)) < 0) {
#endif				
				(void)fprintf(stderr, "Java_javax_comm_CommPortIdentifier_monitorInterJVMDeviceAccessNC: semop error %d!\n", errno);
				return -1;
			}
		}
		else
#endif	/* NCI */
			sleep(pollingTime);
		/* Get the new value of the semaphore. */
			/* Get the current value of the semaphore. */
#ifdef  _POSIX_SEMAPHORES
		if ((sem_getvalue(sem_lookup(semID), &oldVal)) < 0) {
#else
		if ((oldVal = semctl(semID, 0, GETVAL, scarg)) < 0) {
#endif		
			(void)fprintf(stderr, "Java_javax_comm_CommPortIdentifier_monitorInterJVMDeviceAccessNC: semctl error %d!\n", errno);
			return -1;
		}
		if (newVal == oldVal)
			continue;
		/* Get PID of the last process that changed the semaphore.
		   If it is the same JVM, ignore this change.
		 */
			/* Get the current value of the semaphore. */
#ifndef  _POSIX_SEMAPHORES
   /* DLS HACK needs to be changed */
		if ((scpid = semctl(semID, 0, GETPID, scarg)) < 0) {
			(void)fprintf(stderr, "Java_javax_comm_CommPortIdentifier_monitorInterJVMDeviceAccessNC: semctl error %d!\n", errno);
			return -1;
		}
		if (scpid != mypid) {
			/* If locked, send a PORT_OWNED event.
			   Else, send a PORT_UNOWNED event.
			 */
			(*jenv)->CallVoidMethod(jenv, jobj, jm,
						newVal ? cpoPO : cpoPU);
		}
#endif
		oldVal = newVal;
	}	/* end of while() */
} /* Java_javax_comm_CommPortIdentifier_monitorInterJVMDeviceAccessNC */
예제 #19
0
void up(int id) {
        struct sembuf UP = {0, 1, 0};
        int semStatus = semop(id, &UP, 1);
        exit_on_error(semStatus, "UP");
}
예제 #20
0
/*
 * PGSemaphoreLock
 *
 * Lock a semaphore (decrement count), blocking if count would be < 0
 */
void
PGSemaphoreLock(PGSemaphore sema, bool interruptOK)
{
	int			errStatus;
	struct sembuf sops;

	sops.sem_op = -1;			/* decrement */
	sops.sem_flg = 0;
	sops.sem_num = sema->semNum;

	/*
	 * Note: if errStatus is -1 and errno == EINTR then it means we returned
	 * from the operation prematurely because we were sent a signal.  So we
	 * try and lock the semaphore again.
	 *
	 * Each time around the loop, we check for a cancel/die interrupt.	On
	 * some platforms, if such an interrupt comes in while we are waiting, it
	 * will cause the semop() call to exit with errno == EINTR, allowing us to
	 * service the interrupt (if not in a critical section already) during the
	 * next loop iteration.
	 *
	 * Once we acquire the lock, we do NOT check for an interrupt before
	 * returning.  The caller needs to be able to record ownership of the lock
	 * before any interrupt can be accepted.
	 *
	 * There is a window of a few instructions between CHECK_FOR_INTERRUPTS
	 * and entering the semop() call.  If a cancel/die interrupt occurs in
	 * that window, we would fail to notice it until after we acquire the lock
	 * (or get another interrupt to escape the semop()).  We can avoid this
	 * problem by temporarily setting ImmediateInterruptOK to true before we
	 * do CHECK_FOR_INTERRUPTS; then, a die() interrupt in this interval will
	 * execute directly.  However, there is a huge pitfall: there is another
	 * window of a few instructions after the semop() before we are able to
	 * reset ImmediateInterruptOK.	If an interrupt occurs then, we'll lose
	 * control, which means that the lock has been acquired but our caller did
	 * not get a chance to record the fact. Therefore, we only set
	 * ImmediateInterruptOK if the caller tells us it's OK to do so, ie, the
	 * caller does not need to record acquiring the lock.  (This is currently
	 * true for lockmanager locks, since the process that granted us the lock
	 * did all the necessary state updates. It's not true for SysV semaphores
	 * used to implement LW locks or emulate spinlocks --- but the wait time
	 * for such locks should not be very long, anyway.)
	 *
	 * On some platforms, signals marked SA_RESTART (which is most, for us)
	 * will not interrupt the semop(); it will just keep waiting.  Therefore
	 * it's necessary for cancel/die interrupts to be serviced directly by the
	 * signal handler.	On these platforms the behavior is really the same
	 * whether the signal arrives just before the semop() begins, or while it
	 * is waiting.	The loop on EINTR is thus important only for other types
	 * of interrupts.
	 */
	do
	{
		ImmediateInterruptOK = interruptOK;
		CHECK_FOR_INTERRUPTS();
		errStatus = semop(sema->semId, &sops, 1);
		ImmediateInterruptOK = false;
	} while (errStatus < 0 && errno == EINTR);

	if (errStatus < 0)
		elog(FATAL, "semop(id=%d) failed: %m", sema->semId);
}
예제 #21
0
파일: semop04.c 프로젝트: Mellanox/arc_ltp
int main(int ac, char **av)
{
	int lc;			/* loop counter */
	char *msg;		/* message returned from parse_opts */
	int val = 1;		/* value for SETVAL */

	int i;

	/* parse standard options */
	if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) {
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);
	}

	setup();		/* global setup */

	/* The following loop checks looping state if -i option given */

	for (lc = 0; TEST_LOOPING(lc); lc++) {
		/* reset Tst_count in case we are looping */
		Tst_count = 0;

		for (i = 0; i < TST_TOTAL; i++) {

			/* initialize the s_buf buffer */
			s_buf.sem_op = TC[i].op;
			s_buf.sem_flg = TC[i].flg;
			s_buf.sem_num = TC[i].num;

			/* initialize all the primitive semaphores */
			TC[i].get_arr.val = val--;
			if (semctl(sem_id_1, TC[i].num, SETVAL, TC[i].get_arr)
			    == -1) {
				tst_brkm(TBROK, cleanup, "semctl() failed");
			}

			/*
			 * make the call with the TEST macro
			 */

			TEST(semop(sem_id_1, &s_buf, 1));

			if (TEST_RETURN != -1) {
				tst_resm(TFAIL, "call succeeded unexpectedly");
				continue;
			}

			TEST_ERROR_LOG(TEST_ERRNO);

			if (TEST_ERRNO == TC[i].error) {
				tst_resm(TPASS,
					 "expected failure - errno = %d"
					 " : %s", TEST_ERRNO,
					 strerror(TEST_ERRNO));
			} else {
				tst_resm(TFAIL, "unexpected error - "
					 "%d : %s", TEST_ERRNO,
					 strerror(TEST_ERRNO));
			}
		}
	}

	cleanup();

	tst_exit();
}
예제 #22
0
/**
 * The main program
 *
 * Parameters:
 *     - int *compteur  => The counter of messages
 *     - char *tableau  => The table to write in
 *
 * Return:
 *     - int  => The result of the execution
 */
int main(int argc, char** args) {

    // If there are too many arguments
    if (argc > 1) {
        fprintf(stderr, "%s\n", "There are too many arguments. This program requires none.");
        return 1;  // Exit with an error code
    }

    // The variables stored in the shared memory
    int id, *compteur;
    char *tableau;
    key_t key = (key_t)1234;

    // Create the shared memory
    id = shmget(key,TAILLE+sizeof(int),0600|IPC_CREAT);  // Taille => Tableau // sizeof(int) => compteur
    if (id<0) { perror("Error shmget"); exit(1); }


    /* ######################### Semaphore control and cricical zone here ######################### */

    // Create the correct structure for the semaphore implementation
    struct sembuf up = {0, 1, 0};
    struct sembuf down = {0, -1, 0};

    // Get the semaphore table
    int my_sem = semget(key, 1, 0600);

    // If it wasn't created/initialized yet
    if (my_sem == -1) {

        // Create it
        my_sem = semget(key, 1, 0600|IPC_CREAT);

        // Initialize the value of it (only one process at a time)
        if (semctl(my_sem, 0, SETVAL, 1) == -1) { perror("Error semctl"); exit(1); }
    }

    // If after trying to create it an error was thrown
    if (my_sem == -1) { perror("Error semget"); exit(1); }

    // Put DOWN the semaphore
    if (semop(my_sem, &down, 1) == -1) { perror("Error semop DOWN"); exit(1); }

    // Get the value of the counter
    compteur = (int*) shmat(id, 0, 0);
    if (compteur == NULL) { perror("Error shmat"); exit(1); }

    // Get the table's location to store the message
    tableau = (char*)(compteur + 1);

    // Write in the table
    write_in_table(compteur, tableau);

    // Put UP the semaphore
    if (semop(my_sem, &up, 1) == -1) { perror("Error semop UP"); exit(1); }

    /* ######################### End of semaphore control and cricical zone ######################### */


    // Then display it
    printf("%s\n", tableau);

    // Close the shared memory segment (but doesn't delete it!)
    if (shmdt(compteur) < 0) { perror("Error shmdt"); exit(1); }
    return 0;
}
예제 #23
0
파일: worker.c 프로젝트: flw7887/tcpdaemon
int worker( struct TcpdaemonEntryParam *pep , struct TcpdaemonServerEnv *pse )
{
	struct sembuf		sb ;
	fd_set			readfds ;
	
	struct sockaddr		accept_addr ;
	socklen_t		accept_addrlen ;
	int			accept_sock ;
	
	int			nret = 0 ;
	
	while(1)
	{
		DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | waiting for entering accept mutex\n" , pse->index );
		
		/* 进入临界区 */
		memset( & sb , 0x00 , sizeof(struct sembuf) );
		sb.sem_num = 0 ;
		sb.sem_op = -1 ;
		sb.sem_flg = SEM_UNDO ;
		nret = semop( pse->accept_mutex , & sb , 1 ) ;
		if( nret == -1 )
		{
			ErrorLog( __FILE__ , __LINE__ , "WORKER(%ld) | enter accept mutex failed , errno[%d]\n" , pse->index , errno );
			return -1;
		}
		else
		{
			DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | enter accept mutex ok\n" , pse->index );
		}
		
		/* 监控侦听socket或存活管道事件 */
		FD_ZERO( & readfds );
		FD_SET( pse->listen_sock , & readfds );
		FD_SET( pse->alive_pipe->fd[0] , & readfds );
		nret = select( MAX_INT(pse->listen_sock,pse->alive_pipe->fd[0])+1 , & readfds , NULL , NULL , NULL ) ;
		if( nret == -1 )
		{	
			ErrorLog( __FILE__ , __LINE__ , "WORKER(%ld) | select failed , errno[%d]\n" , pse->index , errno );
			break;
		}
		
		if( FD_ISSET( pse->alive_pipe->fd[0] , & readfds ) )
		{
			DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | alive_pipe received quit command\n" , pse->index );
			break;
		}
		
		/* 接受新客户端连接 */
		accept_addrlen = sizeof(struct sockaddr) ;
		memset( & accept_addr , 0x00 , accept_addrlen );
		accept_sock = accept( pse->listen_sock , & accept_addr , & accept_addrlen ) ;
		if( accept_sock == -1 )
		{
			ErrorLog( __FILE__ , __LINE__ , "WORKER(%ld) | accept failed , errno[%d]\n" , pse->index , errno );
			break;
		}
		else
		{
			DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | accept ok , [%d]accept[%d]\n" , pse->index , pse->listen_sock , accept_sock );
		}
		
		if( pep->tcp_nodelay > 0 )
		{
			setsockopt( accept_sock , IPPROTO_TCP , TCP_NODELAY , (void*) & (pep->tcp_nodelay) , sizeof(int) );
		}
		
		if( pep->tcp_linger > 0 )
		{
			struct linger	lg ;
			lg.l_onoff = 1 ;
			lg.l_linger = pep->tcp_linger - 1 ;
			setsockopt( accept_sock , SOL_SOCKET , SO_LINGER , (void *) & lg , sizeof(struct linger) );
		}
		
		/* 离开临界区 */
		memset( & sb , 0x00 , sizeof(struct sembuf) );
		sb.sem_num = 0 ;
		sb.sem_op = 1 ;
		sb.sem_flg = SEM_UNDO ;
		nret = semop( pse->accept_mutex , & sb , 1 ) ;
		if( nret == -1 )
		{
			ErrorLog( __FILE__ , __LINE__ , "WORKER(%ld) | leave accept mutex failed , errno[%d]\n" , pse->index , errno );
			return -1;
		}
		else
		{
			DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | leave accept mutex ok\n" , pse->index );
		}
		
		/* 调用通讯数据协议及应用处理回调函数 */
		DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | 调用tcpmain\n" , pse->index );
		nret = pse->pfunc_tcpmain( pep->param_tcpmain , accept_sock , & accept_addr ) ;
		if( nret < 0 )
		{
			ErrorLog( __FILE__ , __LINE__ , "WORKER(%ld) | tcpmain return[%d]\n" , pse->index , nret );
			return -1;
		}
		else if( nret > 0 )
		{
			WarnLog( __FILE__ , __LINE__ , "WORKER(%ld) | tcpmain return[%d]\n" , pse->index , nret );
		}
		else
		{
			DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | tcpmain return[%d]\n" , pse->index , nret );
		}
		
		/* 关闭客户端连接 */
		close( accept_sock );
		DebugLog( __FILE__ , __LINE__ , "close[%d]\n" , accept_sock );
		
		/* 检查工作进程处理数量 */
		pse->requests_per_process++;
		if( pep->max_requests_per_process != 0 && pse->requests_per_process >= pep->max_requests_per_process )
		{
			InfoLog( __FILE__ , __LINE__ , "WORKER(%ld) | maximum number of processing[%ld][%ld] , ending\n" , pse->index , pse->requests_per_process , pep->max_requests_per_process );
			return -1;
		}
	}
	
	/* 最终离开临界区 */
	memset( & sb , 0x00 , sizeof(struct sembuf) );
	sb.sem_num = 0 ;
	sb.sem_op = 1 ;
	sb.sem_flg = SEM_UNDO ;
	nret = semop( pse->accept_mutex , & sb , 1 ) ;
	if( nret == -1 )
	{
		InfoLog( __FILE__ , __LINE__ , "WORKER(%ld) | leave accept mutex finally failed , errno[%d]\n" , pse->index , errno );
		return -1;
	}
	else
	{
		DebugLog( __FILE__ , __LINE__ , "WORKER(%ld) | leave accept mutex finally ok\n" , pse->index );
	}
	
	return 0;
}
예제 #24
0
/*
 * sem_up - up()'s a semaphore.
 */
static inline void sem_up(int semid)
{
	if (semop(semid, SMwup, 1) == -1) {
		bb_perror_msg_and_die("semop[SMwup]");
	}
}
예제 #25
0
int CSemaphore::CounterDec(int nBCounterSeq )
{
    if (m_nSemID == 0 )
    {
        snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d]", __func__, CACHE_SEM_ERR_COUNTERDEC_NOINIT);
        return CACHE_SEM_ERR_COUNTERDEC_NOINIT;
    }
    int nRet = 0;
START:
    
    if(m_nGoNextSCounter[nBCounterSeq] == 1)    //高位有进位
    {
        for(int i = 0; i < 32; ++i)
        {
            struct sembuf sop[1];
            sop[0].sem_num = GetCounterSemSeq(nBCounterSeq)  ;   
            sop[0].sem_op = -1;
            sop[0].sem_flg = IPC_NOWAIT;
            
            nRet =  semop(m_nSemID, sop, 1);//低位-1
            if(nRet >= 0)
            {
                m_nGoNextSCounter[nBCounterSeq] = 1;
                return 0;
            }
            
            else if(nRet < 0 && errno == EINTR)
            {
                snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, SEM_EINTR, strerror(errno));
                return SEM_EINTR;
            }
            
            else if(nRet < 0 && errno == EAGAIN)//低位不够-1
            {
                struct sembuf sops[2];
                sops[0].sem_num = GetCounterSemSeq(nBCounterSeq)  ;   
                sops[0].sem_op = SEM_VALUE_MAX;
                sops[0].sem_flg = IPC_NOWAIT;
                sops[1].sem_num = GetCounterSWSemSeq(nBCounterSeq)  ;     
                sops[1].sem_op = -1;
                sops[1].sem_flg = IPC_NOWAIT;
                
                nRet =  semop(m_nSemID, sops, 2);   //执行退位  低位加满  高位-1
                if(nRet >= 0)
                {
                    if( GetSemVal(GetCounterSWSemSeq(nBCounterSeq)) > 0 )
                        m_nGoNextSCounter[nBCounterSeq] = 1;
                    else
                        m_nGoNextSCounter[nBCounterSeq] = 0;
                        
                    return 0;
                }
                
                else if(nRet < 0 && errno == EINTR)
                {
                    snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, SEM_EINTR, strerror(errno));
                    return SEM_EINTR;
                }
                
                else if(nRet < 0 && errno == ERANGE)    //低位不能加满
                {
                    continue;
                }
                
                else if(nRet < 0 && errno == EAGAIN)    //高位不能-1 无进位
                {
                    m_nGoNextSCounter[nBCounterSeq] = 0;
                    break;
                }
                
                else
                {
                    snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, CACHE_SEM_ERR_COUNTERDEC_SEMOP2, strerror(errno));
                    return CACHE_SEM_ERR_COUNTERDEC_SEMOP2;
                }
            }
            
            else
            {
                snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, CACHE_SEM_ERR_COUNTERDEC_SEMOP1, strerror(errno));
                return CACHE_SEM_ERR_COUNTERDEC_SEMOP1;
            }
            
        }//end for

        //snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d]", __func__, CACHE_SEM_ERR_COUNTERDEC);
        //return CACHE_SEM_ERR_COUNTERDEC;
    }//end if
    
    struct sembuf sops[2];
    sops[0].sem_num = GetCounterSWSemSeq(nBCounterSeq)  ;   
    sops[0].sem_op = 0;
    sops[0].sem_flg = IPC_NOWAIT;
    sops[1].sem_num = GetCounterSemSeq(nBCounterSeq)  ;     
    sops[1].sem_op = - 1;
    sops[1].sem_flg = 0;
    
    nRet =  semop(m_nSemID, sops, 2);//检查高位    低位-1
    if(nRet >= 0)
    {
        m_nGoNextSCounter[nBCounterSeq] = 0;//高位无进位
        return 0;
    }
    
    else if(nRet < 0 && errno == EINTR)
    {
        snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, SEM_EINTR, strerror(errno));
        return SEM_EINTR;
    }
    
    else if(nRet < 0 && errno == EAGAIN)    //高位有进位
    {
        m_nGoNextSCounter[nBCounterSeq] = 1;
        goto START;
    }
    
    else
    {
        snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, CACHE_SEM_ERR_COUNTERDEC_SEMOP3, strerror(errno));
        return CACHE_SEM_ERR_COUNTERDEC_SEMOP3;
    }
    
    return 0;
}
예제 #26
0
/*
 * sem_down - down()'s a semaphore
 */
static inline void sem_down(int semid)
{
	if (semop(semid, SMwdn, 3) == -1) {
		bb_perror_msg_and_die("semop[SMwdn]");
	}
}
예제 #27
0
int CSemaphore::CounterDec(int nBCounterSeq )
{    
    if (m_nSemID == 0 )
    {
        snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d]", __func__, CACHE_SEM_ERR_COUNTERDEC_NOINIT);
        return CACHE_SEM_ERR_COUNTERDEC_NOINIT;
    }
    
    int nRet = -1;
    for(int i = 0; i < m_nSCounterNum; ++i)
    {
        struct sembuf sops[2];
        memset(sops, 0, sizeof(sops));
        int size = 0;
        
        if(m_nGoNextSCounter[nBCounterSeq] == 0)
        {
            sops[0].sem_num = GetCounterSWSemSeq(nBCounterSeq);
            sops[0].sem_op = 0;                                     
            sops[0].sem_flg = IPC_NOWAIT;
            sops[1].sem_num = GetCounterSemSeq(nBCounterSeq);
            sops[1].sem_op = -1;                                     
            sops[1].sem_flg = 0;
            size = 2;
        }
        else
        {
            sops[0].sem_num = GetCounterSemSeq(nBCounterSeq);
            sops[0].sem_op = -1;                                    
            sops[0].sem_flg = IPC_NOWAIT;
            size = 1;
        }
        
        nRet =  semop(m_nSemID, sops, size);
        
        if(nRet < 0 && errno == EINTR)
        {
            snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, SEM_EINTR, strerror(errno));
            return SEM_EINTR;
        }
        
        else if(nRet < 0 && errno == EAGAIN)
        {
            bool flag = false;
            if( GetSemVal( GetCounterSWSemSeq(nBCounterSeq) ) != 0)         
            {
                m_nGoNextSCounter[nBCounterSeq] = 1;  
                flag = true;
            }
            
            if( GetSemVal( GetCounterSemSeq(nBCounterSeq) ) == 0 )        
            {
                m_nGoNextSCounter[nBCounterSeq] = 0;
                ++ m_nSCounterSeq[nBCounterSeq];
                if(m_nSCounterSeq[nBCounterSeq] >= m_nSCounterNum)
                {
                    m_nSCounterSeq[nBCounterSeq] = 0;
                }
                flag = true;
            }
            
            if(!flag)
            {
                snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d]", __func__, CACHE_SEM_ERR_COUNTERDEC_VAL);
                return CACHE_SEM_ERR_COUNTERDEC_VAL;
            }
            
            continue;
        }
        
        else if(nRet < 0)
        {
            snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d] %s", __func__, CACHE_SEM_ERR_COUNTERDEC_SEMOP, strerror(errno));
            return CACHE_SEM_ERR_COUNTERDEC_SEMOP;
        }
        else
        {
            return 0;
        }
    }
    
    snprintf(m_errmsg, sizeof(m_errmsg), "[%s=%d]", __func__, CACHE_SEM_ERR_COUNTERDEC);
    return CACHE_SEM_ERR_COUNTERDEC;
}
예제 #28
0
int
main(void)
{
	static const int bogus_semid = 0xfdb97531;
	static void * const bogus_sops = (void *) -1L;
	static const size_t bogus_nsops = (size_t) 0xdefaceddeadbeefULL;

	TAIL_ALLOC_OBJECT_CONST_PTR(struct timespec, ts);
	int rc;

	id = semget(IPC_PRIVATE, 1, 0600);
	if (id < 0)
		perror_msg_and_skip("semget");
	atexit(cleanup);

	union semun sem_union = { .val = 0 };
	if (semctl(id, 0, SETVAL, sem_union) == -1)
		perror_msg_and_skip("semctl");

	TAIL_ALLOC_OBJECT_CONST_PTR(struct sembuf, sem_b);
	TAIL_ALLOC_OBJECT_CONST_PTR(struct sembuf, sem_b2);

	rc = semop(bogus_semid, NULL, bogus_nsops);
	printf("semop(%d, NULL, %u) = %s\n",
		bogus_semid, (unsigned) bogus_nsops, sprintrc(rc));

	rc = semop(bogus_semid, bogus_sops, 1);
	printf("semop(%d, %p, %u) = %s\n",
		bogus_semid, bogus_sops, 1, sprintrc(rc));

	sem_b->sem_num = 0;
	sem_b->sem_op = 1;
	sem_b->sem_flg = SEM_UNDO;

	sem_b2->sem_num = 0xface;
	sem_b2->sem_op = 0xf00d;
	sem_b2->sem_flg = 0xbeef;

	rc = semop(bogus_semid, sem_b2, 2);
	printf("semop(%d, [{%hu, %hd, %s%s%#hx}, ... /* %p */], %u) = %s\n",
		bogus_semid, sem_b2->sem_num, sem_b2->sem_op,
		sem_b2->sem_flg & SEM_UNDO ? "SEM_UNDO|" : "",
		sem_b2->sem_flg & IPC_NOWAIT ? "IPC_NOWAIT|" : "",
		(short) (sem_b2->sem_flg & ~(SEM_UNDO | IPC_NOWAIT)),
		sem_b2 + 1, 2, sprintrc(rc));

	if (semop(id, sem_b, 1))
		perror_msg_and_skip("semop, 1");
	printf("semop(%d, [{0, 1, SEM_UNDO}], 1) = 0\n", id);

	sem_b->sem_op = -1;
	if (semop(id, sem_b, 1))
		perror_msg_and_skip("semop, -1");
	printf("semop(%d, [{0, -1, SEM_UNDO}], 1) = 0\n", id);

	rc = semtimedop(bogus_semid, NULL, bogus_nsops, NULL);
	printf("semtimedop(%d, NULL, %u, NULL) = %s\n",
		bogus_semid, (unsigned) bogus_nsops, sprintrc(rc));

	rc = semtimedop(id, sem_b + 1, 1, ts + 1);
	printf("semtimedop(%d, %p, 1, %p) = %s\n",
		id, sem_b + 1, ts + 1, sprintrc(rc));

	ts->tv_sec = 1;
	ts->tv_nsec = 123456789;
	rc = semtimedop(bogus_semid, sem_b2, 2, ts);
	printf("semtimedop(%d, [{%hu, %hd, %s%s%#hx}, ... /* %p */], %u"
		", {tv_sec=%lld, tv_nsec=%llu}) = %s\n",
		bogus_semid, sem_b2->sem_num, sem_b2->sem_op,
		sem_b2->sem_flg & SEM_UNDO ? "SEM_UNDO|" : "",
		sem_b2->sem_flg & IPC_NOWAIT ? "IPC_NOWAIT|" : "",
		(short) (sem_b2->sem_flg & ~(SEM_UNDO | IPC_NOWAIT)),
		sem_b2 + 1, 2,
		(long long) ts->tv_sec, zero_extend_signed_to_ull(ts->tv_nsec),
		sprintrc(rc));

	sem_b->sem_op = 1;
	if (semtimedop(id, sem_b, 1, NULL))
		perror_msg_and_skip("semtimedop, 1");
	printf("semtimedop(%d, [{0, 1, SEM_UNDO}], 1, NULL) = 0\n", id);

	sem_b->sem_op = -1;
	if (semtimedop(id, sem_b, 1, ts))
		perror_msg_and_skip("semtimedop, -1");
	printf("semtimedop(%d, [{0, -1, SEM_UNDO}], 1"
	       ", {tv_sec=%lld, tv_nsec=%llu}) = 0\n", id,
	       (long long) ts->tv_sec, zero_extend_signed_to_ull(ts->tv_nsec));

	sem_b->sem_op = 1;
	ts->tv_sec = 0xdeadbeefU;
	ts->tv_nsec = 0xfacefeedU;
	rc = semtimedop(id, sem_b, 1, ts);
	printf("semtimedop(%d, [{0, 1, SEM_UNDO}], 1"
	       ", {tv_sec=%lld, tv_nsec=%llu}) = %s\n",
	       id, (long long) ts->tv_sec,
	       zero_extend_signed_to_ull(ts->tv_nsec), sprintrc(rc));

	sem_b->sem_op = -1;
	ts->tv_sec = (time_t) 0xcafef00ddeadbeefLL;
	ts->tv_nsec = (long) 0xbadc0dedfacefeedLL;
	rc = semtimedop(id, sem_b, 1, ts);
	printf("semtimedop(%d, [{0, -1, SEM_UNDO}], 1"
	       ", {tv_sec=%lld, tv_nsec=%llu}) = %s\n",
	       id, (long long) ts->tv_sec,
	       zero_extend_signed_to_ull(ts->tv_nsec), sprintrc(rc));

	puts("+++ exited with 0 +++");
	return 0;
}
예제 #29
0
int main(int argc, char *argv[])
{
#ifdef _WIN32
    DWORD numRead;
    DWORD numToWrite;

    if (argc != 2)
    {
        HANDLE namedPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\Pipe"),
            PIPE_ACCESS_DUPLEX,
            PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
            PIPE_UNLIMITED_INSTANCES,
            1024, 1024,
            NMPWAIT_USE_DEFAULT_WAIT,
            NULL);

        if (namedPipe == INVALID_HANDLE_VALUE)
        {
            cout << "Can't create pipe. Error. Press any key to exit " << GetLastError();
            _getch();
            exit(0);
        }

        HANDLE serverSemaphore = CreateSemaphore(NULL, 0, 1, TEXT("serverSemaphore"));
        HANDLE clientSemaphore = CreateSemaphore(NULL, 0, 1, TEXT("clientSemaphore"));

        MyProcess *clientProcess = new MyProcess(argv[0]);

        ConnectNamedPipe(namedPipe, NULL);

        WaitForSingleObject(serverSemaphore, INFINITE);

        char *buffer = NULL;
        buffer = (char *)malloc(sizeof(char) * 1024);

        printf("Server process\n");

        if (!WriteFile(namedPipe, "Ready", 1024, &numToWrite, NULL))
            return 0;

        while (1)
        {
            ReleaseSemaphore(clientSemaphore, 1, NULL);
            WaitForSingleObject(serverSemaphore, INFINITE);

            if (ReadFile(namedPipe, buffer, 1024, &numRead, NULL))
                printf("Client message: %s", buffer);

            if (!strcmp(buffer, "exit"))
            {
                CloseHandle(namedPipe);
                CloseHandle(serverSemaphore);
                free(buffer);
                return 0;
            }

            printf("\nInput message to client: ");
            fflush(stdin);
            gets_s(buffer, 1024);

            if (!WriteFile(namedPipe, buffer, 1024, &numToWrite, NULL))
                break;

            ReleaseSemaphore(clientSemaphore, 1, NULL);

            if (!strcmp(buffer, "exit"))
            {
                CloseHandle(namedPipe);
                CloseHandle(serverSemaphore);

                free(buffer);
                return 0;
            }
        }
        return 0;
    }
    else
    {
        HANDLE serverSemaphore = OpenSemaphore(EVENT_ALL_ACCESS, FALSE, TEXT("serverSemaphore"));
        HANDLE clientSemaphore = OpenSemaphore(EVENT_ALL_ACCESS, FALSE, TEXT("clientSemaphore"));

        HANDLE namedPipe = CreateFile(TEXT("\\\\.\\pipe\\Pipe"),
            GENERIC_READ | GENERIC_WRITE,
            0,
            NULL,
            OPEN_EXISTING,
            0,
            NULL);

        if (namedPipe == INVALID_HANDLE_VALUE)
        {
            printf("Can't create pipe. Error. Press any key to exit", GetLastError());
            _getch();
            exit(0);
        }

        ReleaseSemaphore(serverSemaphore, 1, NULL);

        char *buffer = NULL;
        buffer = (char *)malloc(sizeof(char) * 1024);

        printf("Client process\n");

        while (1)
        {
            WaitForSingleObject(clientSemaphore, INFINITE);

            if (ReadFile(namedPipe, buffer, 1024, &numRead, NULL))
            {
                if (!strcmp(buffer, "exit"))
                {
                    CloseHandle(clientSemaphore);
                    free(buffer);
                    return 0;
                }

                printf("Server message: %s", buffer);

                char input[1024] = { '\0' };
                cout << "\nInput message to server: ";
                fflush(stdin);
                gets_s(input, 1024);

                if (!WriteFile(namedPipe, input, 1024, &numToWrite, NULL))
                    break;

                if (!strcmp(input, "exit"))
                {
                    ReleaseSemaphore(serverSemaphore, 1, NULL);
                    CloseHandle(clientSemaphore);
                    free(buffer);
                    return 0;
                }
            }
            ReleaseSemaphore(serverSemaphore, 1, NULL);
        }
        return 0;
    }

#elif __linux__
    pid_t pid;
    key_t key = ftok("/home/", 0);

    struct sembuf serverSemaphore;
    struct sembuf clientSemaphore;
    int semaphoreId;

    int sharedMemoryId;
    char *segmentPtr;

    if (argc != 2)
    {
        switch (pid = fork())
        {
        case -1:
            printf("Can't fork process %d\n", pid);
            break;
        case 0:
            execlp("gnome-terminal", "gnome-terminal", "-x", argv[0], "1", NULL);
        default:
            if ((sharedMemoryId = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0660)) == -1)
            {
                if ((sharedMemoryId = shmget(key, 1024, 0)) == -1)
                {
                    printf("error\n");
                    exit(1);
                }
            }

            if ((segmentPtr = (char*)shmat(sharedMemoryId, NULL, 0)) == (char*)(-1))
            {
                printf("Can't attach shared memory\n");
                exit(1);
            }

            semaphoreId = semget(key, 1, 0666 | IPC_CREAT);

            if (semaphoreId < 0)
            {
                printf("Can't get semaphore\n");
                exit(EXIT_FAILURE);
            }

            if (semctl(semaphoreId, 0, SETVAL, (int)0) < 0)
            {
                printf("Can't initialize semaphore\n");
                exit(EXIT_FAILURE);
            }

            serverSemaphore.sem_num = 0;
            serverSemaphore.sem_op = 0;
            serverSemaphore.sem_flg = 0;

            printf("Server process: ");

            while (1) {
                char *message = NULL;
                message = (char*)malloc(1024 * sizeof(char));

                semop(semaphoreId, &serverSemaphore, 1);

                printf("\nInput message to client: ");
                fflush(stdin);
                cin >> message;

                strcpy(segmentPtr, message);

                serverSemaphore.sem_op = 3;
                semop(semaphoreId, &serverSemaphore, 1);

                serverSemaphore.sem_op = 0;
                semop(semaphoreId, &serverSemaphore, 1);

                if (!strcmp("exit", message))
                    return 0;

                strcpy(message, segmentPtr);
                printf("Client message: %s\n", message);
            }
            return 0;
        }
    }
    else
    {
        if ((sharedMemoryId = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0660)) == -1)
예제 #30
0
파일: 3.c 프로젝트: fanyonga/JustForFun
main()
{

    struct sembuf P,V;
    union semun arg;

    int arrayid;
    int getid;

    int *array;
    int *get;

    int sumID;
    int *sum;

    sumID=shmget(IPC_PRIVATE,sizeof(int),IPC_CREAT|0666);
    sum=(int *)shmat(sumID,0,0);
    arrayid=shmget(IPC_PRIVATE,sizeof(int)*MAXSHM,IPC_CREAT|0666);
    getid=shmget(IPC_PRIVATE,sizeof(int),IPC_CREAT|0666);

    array=(int *)shmat(arrayid,0,0);
    get=(int *)shmat(getid,0,0);
    *get=0;

    fullid=semget(IPC_PRIVATE,1,IPC_CREAT|0666);
    emptyid=semget(IPC_PRIVATE,1,IPC_CREAT|0666);
    mutexid=semget(IPC_PRIVATE,1,IPC_CREAT|0666);

    arg.val=0;
    if(semctl(fullid,0,SETVAL,arg)==-1)
        perror("semctl setval error");
    arg.val=MAXSHM;
    if(semctl(emptyid,0,SETVAL,arg)==-1)
        perror("semctl setval error");
    arg.val=1;
    if(semctl(mutexid,0,SETVAL,arg)==-1)
        perror("semctl setval error");

    P.sem_num=0;
    P.sem_op=-1;
    P.sem_flg=SEM_UNDO;
    V.sem_num=0;
    V.sem_op=1;
    V.sem_flg=SEM_UNDO;

    if(fork()==0)
    {
        int i=0;
        int set=0;
        while(i<10)
        {
            semop(emptyid,&P,1);
            semop(mutexid,&P,1);
            array[set%MAXSHM]=i+1;
            printf("Productor put number: %d\n",array[set%MAXSHM]);
            set++;
            semop(mutexid,&V,1);
            semop(fullid,&V,1);
            i++;
        }
        sleep(3);
        printf("Productor is over\n");
        exit(0);
    }
    else {

        if(fork()==0)
        {
            while(1)
            {
                if(*get == 10)
                    break;
                semop(fullid,&P,1);
                semop(mutexid,&P,1);
                printf("The ComsumerA get number: %d\n",array[(*get)%MAXSHM]);
                *sum+=array[(*get)%MAXSHM];
                (*get)++;
                semop(mutexid,&V,1);
                semop(emptyid,&V,1);
                sleep(1);
            }
            printf("ComsumerA is over\n");
            exit(0);
        }
        else
        {
            if(fork()==0)
            {
                while(1)
                {
                    if(*get ==10)
                        break;
                    semop(fullid,&P,1);
                    semop(mutexid,&P,1);
                    printf("The ComsumerB get number: %d\n",array[(*get)%MAXSHM]);
                    *sum+=array[(*get)%MAXSHM];
                    (*get)++;
                    semop(mutexid,&V,1);
                    semop(emptyid,&V,1);
                    sleep(1);
                }
                printf("ComsumerB is over\n");
                exit(0);
            }
        }
    }
    wait(0);
    wait(0);
    wait(0);

    shmdt(array);
    shmctl(arrayid,IPC_RMID,0);
    shmdt(get);
    shmctl(getid,IPC_RMID,0);

    semctl(emptyid,IPC_RMID,0);
    semctl(fullid,IPC_RMID,0);
    semctl(mutexid,IPC_RMID,0);
    printf("sum : %d\n",*sum);
    exit(0);
}