当前位置: 首页>>代码示例>>C++>>正文


C++ semctl函数代码示例

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


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

示例1: main

int main(){

  int id; /* Number by which the semaphore is known within a program */
  
  /* The next thing is an argument to the semctl() function. Semctl() 
     does various things to the semaphore depending on which arguments
     are passed. We will use it to make sure that the value of the 
     semaphore is initially 0. */
  
  union semun {
    int val;
    struct semid_ds *buf;
    ushort * array;
  } argument;
  
  argument.val = 1;
  
  /* Create the semaphore with external key KEY if it doesn't already 
     exists. Give permissions to the world. */
  
  id = semget(KEY, 1, 0666 | IPC_CREAT);
  
  /* Always check system returns. */
  
  if(id < 0)
    {
      fprintf(stderr, "Unable to obtain semaphore.\n");
      exit(0);
    }
  
  /* What we actually get is an array of semaphores. The second 
     argument to semget() was the array dimension - in our case
     1. */
  
  /* Set the value of the number 0 semaphore in semaphore array
     # id to the value 0. */
  
  if( semctl(id, 0, SETVAL, argument) < 0)
    {
      fprintf( stderr, "Cannot set semaphore value.\n");
    }
  else
    {
      fprintf(stderr, "Semaphore %d initialized.\n", KEY);
    }
  
  int pid=fork();
  
  if(pid){
    struct sembuf operations[1];
    int retval; /* Return value from semop() */

    /* Get the index for the semaphore with external name KEY. */
    id = semget(KEY, 1, 0666);

    if(id < 0){
      /* Semaphore does not exist. */
      
      fprintf(stderr, "Program sema cannot find semaphore, exiting.\n");
      exit(0);
    }
    operations[0].sem_num = 0;
    /* Which operation? Subtract 1 from semaphore value : */
    operations[0].sem_op = -1;
    /* Set the flag so we will wait : */   
    operations[0].sem_flg = 0;
    

    
    while(1){
      //Process 1

      //wait
      operations[0].sem_op = -1;
      retval = semop(id, operations, 1);


      //critical section
      printf("In critical section P1 ... \n");
      fflush(stdout);
      int stime=2+(rand()/(float)(RAND_MAX))*4;
      printf("Sleeping for %d secs\n",stime);
      sleep(stime);


      printf("Ending critical section P1 ... \n");
      fflush(stdout);

      operations[0].sem_op = 1;
      //signal
      retval = semop(id, operations, 1);

    }
  }else{
    //Process 2
    struct sembuf operations[1];
    int retval; /* Return value from semop() */
    /* Get the index for the semaphore with external name KEY. */
    id = semget(KEY, 1, 0666);
    if(id < 0){
//.........这里部分代码省略.........
开发者ID:philhabell,项目名称:207SE-Operating-Systems,代码行数:101,代码来源:sem_example.c

示例2: 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

示例3: defined


//.........这里部分代码省略.........
    shmbuf.shm_perm.gid = getgid();
    if (shmctl(fdmem, IPC_SET, &shmbuf) == -1)
        FAIL(MM_ERR_CORE|MM_ERR_SYSTEM, "failed to set status of shared memory");
    if (shmctl(fdmem, IPC_RMID, NULL) == -1)
        FAIL(MM_ERR_CORE|MM_ERR_SYSTEM, "failed to remove shared memory in advance");
#endif /* MM_SHMT_IPCSHM */

#if defined(MM_SEMT_FLOCK)
    unlink(fnsem);
    if ((fdsem = open(fnsem, O_RDWR|O_CREAT|O_EXCL, MM_CORE_FILEMODE)) == -1)
        FAIL(MM_ERR_CORE|MM_ERR_SYSTEM, "failed to open semaphore file");
#if defined(F_SETFD) && defined(FD_CLOEXEC)
    if (fcntl(fdsem, F_SETFD, FD_CLOEXEC) == -1)
        FAIL(MM_ERR_CORE|MM_ERR_SYSTEM, "failed to set close-on-exec flag");
#endif
#endif /* MM_SEMT_FLOCK */

#if defined(MM_SEMT_FCNTL)
    unlink(fnsem);
    if ((fdsem = open(fnsem, O_RDWR|O_CREAT|O_EXCL, MM_CORE_FILEMODE)) == -1)
        FAIL(MM_ERR_CORE|MM_ERR_SYSTEM, "failed to open semaphore file");
#if defined(F_SETFD) && defined(FD_CLOEXEC)
    if (fcntl(fdsem, F_SETFD, FD_CLOEXEC) == -1)
        FAIL(MM_ERR_CORE|MM_ERR_SYSTEM, "failed to set close-on-exec flag");
#endif
#endif /* MM_SEMT_FCNTL */

#if defined(MM_SEMT_IPCSEM)
    fdsem = semget(IPC_PRIVATE, 1, IPC_CREAT|IPC_EXCL|S_IRUSR|S_IWUSR);
    if (fdsem == -1 && errno == EEXIST)
        fdsem = semget(IPC_PRIVATE, 1, IPC_EXCL|S_IRUSR|S_IWUSR);
    if (fdsem == -1)
        FAIL(MM_ERR_CORE|MM_ERR_SYSTEM, "failed to acquire semaphore");
    mm_core_semctlarg.val = 0;
    semctl(fdsem, 0, SETVAL, mm_core_semctlarg);
    fdsem_rd = semget(IPC_PRIVATE, 1, IPC_CREAT|IPC_EXCL|S_IRUSR|S_IWUSR);
    if (fdsem_rd == -1 && errno == EEXIST)
        fdsem_rd = semget(IPC_PRIVATE, 1, IPC_EXCL|S_IRUSR|S_IWUSR);
    if (fdsem_rd == -1)
        FAIL(MM_ERR_CORE|MM_ERR_SYSTEM, "failed to acquire semaphore");
    mm_core_semctlarg.val = 0;
    semctl(fdsem_rd, 0, SETVAL, mm_core_semctlarg);
#endif /* MM_SEMT_IPCSEM */

    /*
     * Configure the memory core parameters
     */
    mc = (mem_core *)area;
    mc->mc_size     = size;
    mc->mc_usize    = usersize;
    mc->mc_pid      = getpid();
#if defined(MM_SHMT_IPCSHM)
    mc->mc_fdmem    = fdmem;
#endif
#if defined(MM_SEMT_FLOCK)
    mc->mc_fdsem[0].pid = getpid();
    mc->mc_fdsem[0].fd  = fdsem;
    mc->mc_fdsem[1].pid = 0;
    mc->mc_fdsem[1].fd  = -1;
#else
    mc->mc_fdsem = fdsem;
#endif
#if defined(MM_SEMT_BEOS)
    mc->mc_semid = create_sem(0, "mm_semid");
    mc->mc_ben = 0;
#endif
开发者ID:mschwartz,项目名称:mm,代码行数:67,代码来源:mm_core.c

示例4: main

int main (int argc, char* argv[])
{
	key_t klucz = ftok("./../..",'L');
	
	if(klucz == -1)
	{
		fprintf(stderr,"KONSUMENT: Blad tworzenia klucza dla zbioru semaforów!\n");
		exit(3);
	}
	else
		fprintf(stdout,"KONSUMENT: Wartosc wygenerowanego klucza dla zbioru semaforow: %ld\n", klucz);
	
	// przyłączanie zbioru semaforów:	
	int ilosc_sem = 4;
	int id_semafor = semget(klucz, ilosc_sem, IPC_CREAT|0600);
	if (id_semafor == -1)
	{
		fprintf(stderr,"KONSUMENT: Blad przyłączania zbioru semaforow!\n");
		exit(EXIT_FAILURE);
	}
	else
		fprintf(stdout,"KONSUMENT: Zbior semaforow przyłączony, id= %d\n", id_semafor);


	FILE* wyjscie = fopen("out.txt", "w");
	if(wyjscie == 0)
	{
		fprintf(stderr,"KONSUMENT: Blad otwierania pliku wyjsciowego!\n");
		exit(EXIT_FAILURE);
	}
	else
		fprintf(stdout, "KONSUMENT: Plik wyjsciowy otwarty!\n");
	
	// przylaczenie segmentu pamięci dzielonej
	int id_pamiec = shmget(klucz, 4, IPC_CREAT|0600);
	if (id_pamiec == -1)
	{
		fprintf(stderr, "KONSUMENT: Blad przylaczenia segmentu pamieci dzielonej!\n");
		exit(EXIT_FAILURE);
	}
	else
		fprintf(stdout, "KONSUMENT: Pomyslnie przylaczono segment pamieci dzielonej o ID: %d\n", id_pamiec);
	
	//uzyskanie adresu segmentu pamieci dzielonej	
	char* adres=(char*)shmat(id_pamiec, 0, 0);
	if (*adres==-1)
	{
		fprintf(stderr, "KONSUMENT: Blad uzyskania dostepu do segmentu pamieci dzielonej!\n");
		exit(EXIT_FAILURE);
	}
	else
		fprintf(stdout, "KONSUMENT: Pomyslnie uzyskano dostep do segmentu pamieci dzielonej: %X\n", adres);
	
	char znak;
	int status;
	
	while(1)
	{			
		opusc_semafor(id_semafor, 0);
		
		if(semctl(id_semafor, 2, GETVAL, NULL) <= 0)
			break;
		
		znak=*adres;
		
		srand(time(NULL));
		//usleep(rand() % 100);
		
		fputc(znak, wyjscie);
		
		if(ferror(wyjscie))
			fprintf(stderr, "PRODUCENT: Blad zapisu znaku do pliku wejsciowego!\n");
				
		podnies_semafor(id_semafor, 1);	
	}
	
	if(status < 0)
	{
		fprintf(stderr,"KONSUMENT: Blad pobierania wartosci semafora nr 2\n"); 
		exit(EXIT_FAILURE);
	}
		
	fprintf(stdout,"KONSUMENT: zakonczono kopiowanie znakow\n");
	podnies_semafor(id_semafor, 3);	
	//zamkniecie pliku
	if(fclose(wyjscie) == EOF) 
	{
		fprintf(stderr,"PRODUCENT: Blad zamykania pliku wyjsciowego\n"); 
		exit(EXIT_FAILURE);
	}
	else
		fprintf(stdout, "KONSUMENT: Pomyslnie zamknieto plik wyjsciowy\n");
		
	return 0;
}
开发者ID:Qhoros,项目名称:C-LINUX,代码行数:95,代码来源:konsument.c

示例5: 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

示例6: 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

示例7: shmfifo_create

/**
 * Returns a data-structure for accessing a shared-memory FIFO. Creates the
 * FIFO is it doesn't already exist.
 *
 * @retval !NULL        Pointer the data-structure for accessing the
 *                      shared-memory FIFO.
 * @retval NULL         Failure. An error message is logged.
 */
ShmHandle*
shmfifo_create(
    const int   npages,         /**< size of the FIFO in pages */
    const int   privsz,         /**< <size of the private portion of the FIFO
                                 in bytes */
    const int   nkey)           /**< Partial key associated with the FIFO  or
                                 \c -1 to obtain a private, shared-memory
                                 FIFO. */
{
    int                 shmSize = npages*getpagesize();
    int                 shmid;
    struct shmhandle*   shm = NULL;     /* default failure */
    key_t               key;

    if (nkey == -1) {
        shmid = shmget(IPC_PRIVATE, shmSize,
                IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
    }
    else {
        key = (key_t)(DVBS_ID + nkey);
        /*
         * IPC_EXCL creates an error condition if the memory already exists...
         * we can use the existing memory if the program has not changed the
         * size of the segment or the private structure size
         */
        shmid = shmget(key, shmSize,
            IPC_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
    }

    if (shmid == -1) {
        log_syserr("shmget() failure: npages=%d, nkey=%d",
            npages, nkey);
    }
    else {
        /* Temporarily attach to initialize the control structure. */
        struct shmprefix*       p = (struct shmprefix*)shmat(shmid, 0, 0);

        if (p == (void*)-1) {
            log_syserr("shmat() failure: id=%d", shmid);
        }
        else {
            int     semid;

            p->read = p->write = sizeof(struct shmprefix) + privsz;
            p->sz = shmSize;
            p->privsz = privsz;

            (void)memset((char*)p + sizeof(struct shmprefix), 0, privsz);
            (void)shmdt(p);

            p = NULL;

            /* Get semaphore */
            if (nkey == -1) {
                semid = semget(IPC_PRIVATE, SI_SEM_COUNT,
                    (IPC_CREAT | IPC_EXCL) + 0600);
            }
            else {
                /*
                 * IPC_EXCL not used in order to get existing semaphore if
                 * possible.
                 */
                semid = semget(key, SI_SEM_COUNT, IPC_CREAT + 0660);
            }

            if (semid == -1) {
                log_syserr("semget() failure");
            }
            else {
                unsigned short      values[SI_SEM_COUNT];
                union semun         arg;

                log_debug("shmfifo_create(): Got semaphore: pid=%d, semid=%d",
                    getpid(), semid);

                values[SI_LOCK] = 1;
                values[SI_WRITER] = 0;
                values[SI_READER] = 0;
                arg.array = values;

                if (semctl(semid, 0, SETALL, arg) == -1) {
                    log_syserr("semctl() failure: semid=%d",
                        semid);
                }
                else {
                    shm = shmfifo_new();

                    if (NULL != shm) {
                        shm->sid = shmid;
                        shm->privsz = privsz;
                        shm->sz = shmSize;
                        shm->semid = semid;
//.........这里部分代码省略.........
开发者ID:Unidata,项目名称:LDM,代码行数:101,代码来源:shmfifo.c

示例8:

	~Semid1()
	{
		if (semctl(semid,0,IPC_RMID)==-1)throw_nynn_exception(errno,NULL);
	}
开发者ID:iieplatform,项目名称:nynn_mm,代码行数:4,代码来源:nynn_ipc.hpp

示例9: ftok

/*!
    \internal

    Setup unix_key
 */
key_t QSystemSemaphorePrivate::handle(QSystemSemaphore::AccessMode mode)
{
    if (key.isEmpty()){
        errorString = QCoreApplication::tr("%1: key is empty", "QSystemSemaphore").arg(QLatin1String("QSystemSemaphore::handle:"));
        error = QSystemSemaphore::KeyError;
        return -1;
    }

    // ftok requires that an actual file exists somewhere
    if (-1 != unix_key)
        return unix_key;

    // Create the file needed for ftok
    int built = QSharedMemoryPrivate::createUnixKeyFile(fileName);
    if (-1 == built) {
        errorString = QCoreApplication::tr("%1: unable to make key", "QSystemSemaphore").arg(QLatin1String("QSystemSemaphore::handle:"));
        error = QSystemSemaphore::KeyError;
        return -1;
    }
    createdFile = (1 == built);

    // Get the unix key for the created file
    unix_key = ftok(QFile::encodeName(fileName).constData(), 'Q');
    if (-1 == unix_key) {
        errorString = QCoreApplication::tr("%1: ftok failed", "QSystemSemaphore").arg(QLatin1String("QSystemSemaphore::handle:"));
        error = QSystemSemaphore::KeyError;
        return -1;
    }

    // Get semaphore
    semaphore = semget(unix_key, 1, 0666 | IPC_CREAT | IPC_EXCL);
    if (-1 == semaphore) {
        if (errno == EEXIST)
            semaphore = semget(unix_key, 1, 0666 | IPC_CREAT);
        if (-1 == semaphore) {
            setErrorString(QLatin1String("QSystemSemaphore::handle"));
            cleanHandle();
            return -1;
        }
    } else {
        createdSemaphore = true;
        // Force cleanup of file, it is possible that it can be left over from a crash
        createdFile = true;
    }

    if (mode == QSystemSemaphore::Create) {
        createdSemaphore = true;
        createdFile = true;
    }

    // Created semaphore so initialize its value.
    if (createdSemaphore && initialValue >= 0) {
        qt_semun init_op;
        init_op.val = initialValue;
        if (-1 == semctl(semaphore, 0, SETVAL, init_op)) {
            setErrorString(QLatin1String("QSystemSemaphore::handle"));
            cleanHandle();
            return -1;
        }
    }

    return unix_key;
}
开发者ID:Akheon23,项目名称:chromecast-mirrored-source.vendor,代码行数:68,代码来源:qsystemsemaphore_unix.cpp

示例10: main

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

示例11: qsem_check

/**
 * Get the status of semaphore
 *
 * @param semid     semaphore identifier
 * @param semno     semaphore number
 *
 * @return true for the flag on, false for the flag off
 */
bool qsem_check(int semid, int semno) {
    if (semctl(semid, semno, GETVAL, 0) == 0)
        return true;  // locked
    return false;  // unlocked
}
开发者ID:Cybsloth,项目名称:qlibc,代码行数:13,代码来源:qsem.c

示例12: main

int main(int argc, char *argv[])
{

    //定义共享缓冲区及其信号灯
    int readbuf_id = shmget(IPC_PRIVATE, CACHE_LENGTH + sizeof(unsigned),
                            IPC_CREAT | IPC_EXCL | 0666);
    int rbuf_empty = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | 0666);
    int rbuf_max = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | 0666);
    int writebuf_id = shmget(IPC_PRIVATE, CACHE_LENGTH + sizeof(unsigned),
                             IPC_CREAT | IPC_EXCL | 0666);
    int wbuf_empty = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | 0666);
    int wbuf_max = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | 0666);

    int finish_id = semget(IPC_PRIVATE, 1, IPC_CREAT | IPC_EXCL | 0666);

    int get_id = 0;
    int put_id = 0;
    int copy_id = 0;

    union semun semopts;
    FILE *out;
    FILE *in;
    int n;

    //打开源和目标文件
    if (argc != 3)
    {
        puts("arguments error");
        return 0;
    }
    if ((in = fopen(argv[1], "rb")) == NULL)
    {
        puts("can't open input file");
        return 0;
    }
    if ((out = fopen(argv[2], "wb")) == NULL)
    {
        puts("can't open output file");
        fclose(in);
        return 0;
    }

    //信号灯赋值
    semopts.val = 1;
    semctl(rbuf_empty, 0, SETVAL, semopts);
    semctl(wbuf_empty, 0, SETVAL, semopts);
    semopts.val = 0;
    semctl(rbuf_max, 0, SETVAL, semopts);
    semctl(wbuf_max, 0, SETVAL, semopts);
    semctl(finish_id, 0, SETVAL, semopts);
    /*semctl(part_over, 0, SETVAL, semopts);*/
    /*semctl(over, 0, SETVAL, semopts);*/

    // get
    if ((get_id = fork()) == 0)
    {
        unsigned char *s = shmat(readbuf_id, 0, 0);
        puts("get:start to get");
        do
        {
            P(rbuf_empty, 0);

            //加入copy
            n = fread(s + sizeof(unsigned), 1, CACHE_LENGTH, in);
            /*n = fread(s + sizeof(unsigned),  1, 2, in);*/
            printf("read: %d\n", n);
            /*putchar('\n');*/

            *(unsigned *)s = n;
            /*fwrite(s + sizeof(unsigned),  1, *(unsigned *)s, stdout);*/
            V(rbuf_max, 0);

            if (*(unsigned *)s == 0)
                break;
        } while (1);
        fclose(in);
        /*sleep(5);*/
        P(finish_id, 0);
        shmdt(s);

        //请加入保证三个进程同步结束的机制
        puts("get: get ended");
        return 0;
    }
    // copy
    if ((copy_id = fork()) == 0)
    {
        unsigned char *s1 = shmat(readbuf_id, 0, 0);
        unsigned char *s2 = shmat(writebuf_id, 0, 0);

        char buf[CACHE_LENGTH + sizeof(unsigned)];
        puts("copy: start to copy");
        do
        {
            P(rbuf_max, 0);

            //加入内容
            n = *(unsigned *)s1;
            printf("copy: %d\n", n);
            memcpy(buf, s1, CACHE_LENGTH + sizeof(unsigned));
//.........这里部分代码省略.........
开发者ID:Alexoner,项目名称:linux-snippet,代码行数:101,代码来源:producer_consumer.c

示例13: uv_sem_destroy

void uv_sem_destroy(uv_sem_t* sem) {
  if (-1 == semctl(*sem, 0, IPC_RMID))
    abort();
}
开发者ID:hpcc-systems,项目名称:libuv,代码行数:4,代码来源:thread.c

示例14: main

int main (int argc, char ** argv)
{
    int semid;

    key = rand();

#ifndef DO_BENCH
    printf("Semaphore key: 0x%8x\n", key);
#endif

    /* server run first and client run later */
    if (argc == 2 && strcmp(argv[1], "serial") == 0) {
        mode = SERIAL;
        if (fork() == 0)
            server();
        wait(NULL);
        if (fork() == 0)
            client();
        wait(NULL);
    }

    if ((semid = semget(key, 2, 0600|IPC_CREAT)) < 0) {
        perror("semget");
        exit(1);
    }

    /* server run first and client run later (in the same process) */
    if (argc == 2 && strcmp(argv[1], "in-process") == 0) {
        mode = IN_PROCESS;
        server();
        client();
        semctl(semid, 0, IPC_RMID);
        return 0;
    }

    pipe(pipefds);

    /* server to be the parent and client to be the child */
    if (argc == 1) {
        if (fork() == 0)
            client();
        else
            server();
    }

    /* client to be the parent and server to be the child */
    if (argc == 2 && strcmp(argv[1], "reverse") == 0) {
        if (fork() == 0)
            server();
        else
            client();
    }

    /* both client and server are children */
    if (argc == 2 && strcmp(argv[1], "children") == 0) {
        if (fork() == 0)
            server();
        if (fork() == 0)
            client();
        wait(NULL);
        wait(NULL);
    }

    semctl(semid, 0, IPC_RMID);

    return 0;
}
开发者ID:oscarlab,项目名称:graphene,代码行数:67,代码来源:sem.c

示例15: program

/*---------------------------------------------------------------------+
|                               main                                   |
| ==================================================================== |
|                                                                      |
| Function:  Main program  (see prolog for more details)               |
|                                                                      |
| Returns:   (0)  Successful completion                                |
|            (-1) Error occurred                                       |
|                                                                      |
+---------------------------------------------------------------------*/
int main(int argc, char **argv)
{
	uid_t uid = getuid();	/* User's user id */
	gid_t gid = getgid();	/* User's group id */
	int semid;		/* Unique semaphore id */
	int nsems = NUM_SEMAPHORES;	/* Number of semaphores to create */
	struct semid_ds exp_semdata;	/* Expected semaphore values */
	union semun exp_semdatap;
	struct semid_ds act_semdata;	/* Actual semaphore values */
	union semun act_semdatap;

	exp_semdatap.buf = &exp_semdata;
	act_semdatap.buf = &act_semdata;

	umask(0000);

	/* SET semid_ds STRUCTURE TO DESIRED VALUES........ */

	/*
	 * Initialize the "expected" sempahore value structure
	 */
	exp_semdata.sem_perm.cuid = exp_semdata.sem_perm.uid = uid;
	exp_semdata.sem_perm.cgid = exp_semdata.sem_perm.gid = gid;
	exp_semdata.sem_perm.mode = 0660;
	exp_semdata.sem_nsems = nsems;

	/*
	 * Create a semaphore, set the semaphore fields and then
	 * retrieve the fields.
	 */
	if ((semid = semget(IPC_PRIVATE, nsems, IPC_CREAT | 0666)) < 0)
		sys_error("semget (IPC_PRIVATE) failed", __LINE__);

	if (semctl(semid, nsems, IPC_SET, exp_semdatap) < 0)
		sys_error("semctl (IPC_SET) failed", __LINE__);

	if (semctl(semid, nsems, IPC_STAT, act_semdatap) < 0)
		sys_error("semctl (IPC_STAT) failed", __LINE__);

	/*
	 * Verify that the semaphore fields were set correctly
	 */
	if (act_semdata.sem_perm.cuid != exp_semdata.sem_perm.cuid)
		error("sem_perm.cuid field was not set!", __LINE__);
	if (act_semdata.sem_perm.uid != exp_semdata.sem_perm.uid)
		error("sem_perm.uid field was not set!", __LINE__);
	if (act_semdata.sem_perm.cgid != exp_semdata.sem_perm.cgid)
		error("sem_perm.cgid field was not set!", __LINE__);
	if (act_semdata.sem_perm.gid != exp_semdata.sem_perm.gid)
		error("sem_perm.gid field was not set!", __LINE__);
	if (act_semdata.sem_perm.mode != exp_semdata.sem_perm.mode)
		error("sem_perm.mode field was not set!", __LINE__);
	if (act_semdata.sem_nsems != exp_semdata.sem_nsems)
		error("sem_nsems field was not set!", __LINE__);

	/*
	 * Print out the id of the newly created semaphore for comparison
	 * with the 'ipcs -s' command and then exit.
	 */
	printf("%d\n", semid);

	return (0);
}
开发者ID:Altiscale,项目名称:sig-core-t_ltp,代码行数:73,代码来源:semaphore_test_01.c


注:本文中的semctl函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。