• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ semop函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中semop函数的典型用法代码示例。如果您正苦于以下问题:C++ semop函数的具体用法?C++ semop怎么用?C++ semop使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了semop函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: semid_get

/* 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;
}
开发者ID:OpenSharp,项目名称:NDceRpc,代码行数:98,代码来源:semc.c


示例2: snprintf

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;
}
开发者ID:YangChunQuan,项目名称:Code,代码行数:82,代码来源:Semaphore.cpp


示例3: main

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 {
  
//.........这里部分代码省略.........
开发者ID:chrapkowski,项目名称:so-ipc,代码行数:101,代码来源:sys_v_shm.c


示例4: main

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;
}
开发者ID:ahui108,项目名称:broccoli,代码行数:77,代码来源:shm_srv.cpp


示例5: main

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;
}
开发者ID:Chinmay-at-git,项目名称:M1UPS,代码行数:80,代码来源:exo2.c


示例6: down

void down(int id) {
        struct sembuf DOWN = {0, -1, 0};
        int semStatus = semop(id, &DOWN, 1);
        exit_on_error(semStatus, "DOWN");
}
开发者ID:GGfpc,项目名称:UBERlinux,代码行数:5,代码来源:UberCondutor.c


示例7: main

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;
}
开发者ID:saikatbsk,项目名称:daily-dose-of-code,代码行数:67,代码来源:sharedMemWithSemaphore.c


示例8: main

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);
}
开发者ID:vidyalakshmir,项目名称:Server-Client,代码行数:86,代码来源:serv2.c


示例9: restore_data


//.........这里部分代码省略.........
	//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;
}
开发者ID:North114,项目名称:SocketReceiver,代码行数:101,代码来源:socket_receiver_v02.c


示例10: ce_sem_create

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;
}
开发者ID:shajf,项目名称:cloudeagle,代码行数:62,代码来源:ce_sem.c


示例11: semget

/*
** 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
//.........这里部分代码省略.........
开发者ID:North114,项目名称:SocketReceiver,代码行数:101,代码来源:socket_receiver_v02.c


示例12: sem_down

/*
 * sem_down - down()'s a semaphore
 */
static inline void sem_down(int semid)
{
	if ( semop(semid, SMrdn, 2) == -1 )
		error_exit("semop[SMrdn]");
}
开发者ID:earthGavinLee,项目名称:hg556a_source,代码行数:8,代码来源:logread.c


示例13: sem_up

/*
 * sem_up - up()'s a semaphore.
 */
static inline void sem_up(int semid)
{
	if ( semop(semid, SMrup, 1) == -1 )
		error_exit("semop[SMrup]");
}
开发者ID:earthGavinLee,项目名称:hg556a_source,代码行数:8,代码来源:logread.c


示例14: testaccess_ipc

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;
//.........这里部分代码省略.........
开发者ID:8l,项目名称:rose,代码行数:101,代码来源:syscall_rt.18.c


示例15: hijo

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;
//.........这里部分代码省略.........
开发者ID:jouyt,项目名称:Universidad,代码行数:101,代码来源:productor.c


示例16: try_sem

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);
}
开发者ID:Zex,项目名称:walaxsi,代码行数:95,代码来源:walaxsi.c


示例17: getpid

/*
 * 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);
//.........这里部分代码省略.........
开发者ID:GreenCom-Networks,项目名称:kura,代码行数:101,代码来源:cygCommPortIdentifier.c


示例18: up

void up(int id) {
        struct sembuf UP = {0, 1, 0};
        int semStatus = semop(id, &UP, 1);
        exit_on_error(semStatus, "UP");
}
开发者ID:GGfpc,项目名称

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ send函数代码示例发布时间:2022-05-30
下一篇:
C++ semget函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap