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

C++ sem_unlink函数代码示例

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

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



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

示例1: semcompat_new

sem_t * semcompat_new(
    int pshared,
    unsigned int value)
{
    sem_t * ret;
    int errno_save;

    if (pthread_once(&support_unnamed_initialized, initialize_support_unnamed) != 0)
    {
        // errno is set by pthread_once
        return SEM_FAILED;
    }

    if (support_unnamed)
    {
        ret = malloc(sizeof(sem_t));
        if (ret == NULL)
        {
            // errno is set by malloc
            return SEM_FAILED;
        }

        if (sem_init(ret, pshared, value) != 0)
        {
            errno_save = errno;
            free(ret);
            errno = errno_save;
            return SEM_FAILED;
        }

        return ret;
    }
    else
    {
        size_t i;
        char name[SEM_NAME_SIZE];

        for (i = 0; i < SEM_OPEN_MAX_TRIES; ++i)
        {
            make_sem_name(name);

            ret = sem_open(name, O_CREAT | O_EXCL, 0600, value);
            if (ret == SEM_FAILED)
            {
                if (errno == EEXIST)
                {
                    // try another name
                    continue;
                }
                else
                {
                    // errno is set by sem_open
                    return SEM_FAILED;
                }
            }
            else
            {
                // Now that it's open, we don't want any other processes to
                // access it by name.
                if (sem_unlink(name) != 0)
                {
                    LOG(LOG_WARNING,
                        "failed to unlink semaphore %s, continuing anyway",
                        name);
                }

                return ret;
            }
        }

        LOG(LOG_ERR, "failed to create a semaphore after %d tries",
            SEM_OPEN_MAX_TRIES);
        errno = EAGAIN;
        return SEM_FAILED;
    }
}
开发者ID:dseomn,项目名称:rpstir,代码行数:76,代码来源:semaphore_compat.c


示例2: PJ_DEF

/*
 * pj_sem_create()
 */
PJ_DEF(pj_status_t) pj_sem_create( pj_pool_t *pool, 
				   const char *name,
				   unsigned initial, 
				   unsigned max,
				   pj_sem_t **ptr_sem)
{
#if PJ_HAS_THREADS
    pj_sem_t *sem;

    PJ_CHECK_STACK();
    PJ_ASSERT_RETURN(pool != NULL && ptr_sem != NULL, PJ_EINVAL);

    sem = PJ_POOL_ALLOC_T(pool, pj_sem_t);
    PJ_ASSERT_RETURN(sem, PJ_ENOMEM);

#if defined(PJ_DARWINOS) && PJ_DARWINOS!=0
    /* MacOS X doesn't support anonymous semaphore */
    {
	char sem_name[PJ_GUID_MAX_LENGTH+1];
	pj_str_t nam;

	/* We should use SEM_NAME_LEN, but this doesn't seem to be 
	 * declared anywhere? The value here is just from trial and error
	 * to get the longest name supported.
	 */
#	define MAX_SEM_NAME_LEN	23

	/* Create a unique name for the semaphore. */
	if (PJ_GUID_STRING_LENGTH <= MAX_SEM_NAME_LEN) {
	    nam.ptr = sem_name;
	    pj_generate_unique_string(&nam);
	    sem_name[nam.slen] = '\0';
	} else {
	    pj_create_random_string(sem_name, MAX_SEM_NAME_LEN);
	    sem_name[MAX_SEM_NAME_LEN] = '\0';
	}

	/* Create semaphore */
	sem->sem = sem_open(sem_name, O_CREAT|O_EXCL, S_IRUSR|S_IWUSR, 
			    initial);
	if (sem->sem == SEM_FAILED)
	    return PJ_RETURN_OS_ERROR(pj_get_native_os_error());

	/* And immediately release the name as we don't need it */
	sem_unlink(sem_name);
    }
#else
    sem->sem = PJ_POOL_ALLOC_T(pool, sem_t);
    if (sem_init( sem->sem, 0, initial) != 0) 
	return PJ_RETURN_OS_ERROR(pj_get_native_os_error());
#endif
    
    /* Set name. */
    if (!name) {
	name = "sem%p";
    }
    if (strchr(name, '%')) {
	pj_ansi_snprintf(sem->obj_name, PJ_MAX_OBJ_NAME, name, sem);
    } else {
	strncpy(sem->obj_name, name, PJ_MAX_OBJ_NAME);
	sem->obj_name[PJ_MAX_OBJ_NAME-1] = '\0';
    }

    PJ_LOG(6, (sem->obj_name, "Semaphore created"));

    *ptr_sem = sem;
    return PJ_SUCCESS;
#else
    *ptr_sem = (pj_sem_t*)1;
    return PJ_SUCCESS;
#endif
}
开发者ID:aemonfly,项目名称:android-client,代码行数:75,代码来源:os_core_unix.c


示例3: WelsEventClose

WELS_THREAD_ERROR_CODE    WelsEventClose (WELS_EVENT* event, str_t* event_name) {
  WELS_THREAD_ERROR_CODE err = sem_close (event);	// match with sem_open
  if (event_name)
    sem_unlink (event_name);
  return err;
}
开发者ID:pps83,项目名称:openh264,代码行数:6,代码来源:WelsThreadLib.cpp


示例4: exit_fun

void exit_fun() {
    shm_unlink(MEM_NAME);
    sem_close(sem);
    sem_unlink(SEM_NAME);
}
开发者ID:maciejmarczak,项目名称:studies,代码行数:5,代码来源:main.c


示例5: sem_unlink

system_layer2_multithreaded_callback::~system_layer2_multithreaded_callback()
{
    sem_unlink("/waiting_sem");
    sem_unlink("/shutdown_sem");
}
开发者ID:AVnu,项目名称:avdecc-lib,代码行数:5,代码来源:system_layer2_multithreaded_callback.cpp


示例6: nsem_test

void nsem_test(void)
{
	pthread_t peer = (pthread_t)0;
#ifdef SDCC
	pthread_addr_t result;
#endif
	FAR sem_t *sem1;
	FAR sem_t *sem2;
	struct sched_param sparam;
	int prio_min;
	int prio_max;
	int prio_mid;
	pthread_attr_t attr;
	int status;

	/* Open semaphore 2.  We will create that one */

	printf("nsem_test: Create semaphore 1 with value == 0\n");
	sem1 = sem_open(SEM1_NAME, O_CREAT | O_EXCL, 0644, 0);
	if (sem1 == (FAR sem_t *)ERROR) {
		int errcode = errno;
		printf("nsem_peer: ERROR: sem_open(1) failed: %d\n", errcode);
		return;
	}

	/* Start the peer thread */

	printf("nsem_test: Starting peer peer\n");
	status = pthread_attr_init(&attr);
	if (status != OK) {
		printf("nsem_test: pthread_attr_init failed, status=%d\n",  status);
	}

	prio_min = sched_get_priority_min(SCHED_FIFO);
	prio_max = sched_get_priority_max(SCHED_FIFO);
	prio_mid = (prio_min + prio_max) / 2;

	sparam.sched_priority = (prio_mid + prio_max) / 2;
	status = pthread_attr_setschedparam(&attr, &sparam);
	if (status != OK) {
		printf("nsem_test: ERROR: pthread_attr_setschedparam failed, status=%d\n",  status);
	} else {
		printf("nsem_test: Set peer priority to %d\n",  sparam.sched_priority);
	}

	status = pthread_create(&peer, &attr, nsem_peer, NULL);
	if (status != 0) {
		printf("nsem_test: ERROR: Peer thread creation failed: %d\n",  status);
		return;
	}

	/* Wait for the peer to post semaphore 1 */

	printf("nsem_test: Wait on semaphore 1\n");
	status = sem_wait(sem1);
	if (status < 0) {
		int errcode = errno;
		printf("nsem_test: ERROR: sem_wait(1) failed: %d\n",  errcode);
		pthread_cancel(peer);
		return;
	}

	/* Close sem1.  It should already have been unlinked by the nsem_peer */

	printf("nsem_test: Close semaphore 1\n");
	sem_close(sem1);

	/* Open semaphore 2.  This should have already been created by
	 * nsem_peer().
	 */

	printf("nsem_test: Open semaphore 2\n");
	sem2 = sem_open(SEM2_NAME, 0);
	if (sem2 == (FAR sem_t *)ERROR) {
		int errcode = errno;
		printf("nsem_test: ERROR: sem_open(2) failed: %d\n", errcode);
		pthread_cancel(peer);
		return;
	}

	/* Wait for the peer to post semaphore 2 */

	printf("nsem_test: Wait on semaphore 2\n");
	status = sem_wait(sem2);
	if (status < 0) {
		int errcode = errno;
		printf("nsem_test: ERROR: sem_wait(1) failed: %d\n",  errcode);
		pthread_cancel(peer);
		return;
	}

	/* Close and unlink semaphore 2 */

	printf("nsem_test: Close and unlink semaphore 2\n");
	sem_close(sem2);
	sem_unlink(SEM2_NAME);

#ifdef SDCC
	if (peer != (pthread_t)0) {
		pthread_join(peer, &result);
//.........这里部分代码省略.........
开发者ID:carhero,项目名称:TizenRT,代码行数:101,代码来源:nsem.c


示例7: malloc

IPC *ipc_open(int semflags, int memflags) {
  IPC *ipp = malloc(sizeof(IPC));
  memset(ipp, 0, sizeof(IPC));
  char buf[4096];
  int written_len = 0;

  // FILE *log = stdout;  

  //fprintf(log, "logging\n");
  if (semflags & O_CREAT) {
    sem_unlink(SEM_NAME "CALLER");
    sem_unlink(SEM_NAME "SERVER");
    sem_unlink(SEM_NAME "REPLY");

    ipp->mutex_caller = sem_open(SEM_NAME "CALLER", semflags, 0666, 1);
    ipp->mutex_server = sem_open(SEM_NAME "SERVER", semflags, 0666, 0);
    ipp->mutex_reply = sem_open(SEM_NAME "REPLY", semflags, 0666, 0);
  } else {
    ipp->mutex_caller = sem_open(SEM_NAME "CALLER", semflags);
    ipp->mutex_server = sem_open(SEM_NAME "SERVER", semflags);
    ipp->mutex_reply = sem_open(SEM_NAME "REPLY", semflags);
  }
  if (ipp->mutex_caller == SEM_FAILED || 
      ipp->mutex_server == SEM_FAILED || 
      ipp->mutex_reply == SEM_FAILED) {
    error("Open semaphore failed: %s: %s\n", SEM_NAME, strerror(errno));
    goto sem_fail;
  }

  ipp->fd = open(SHM_PATH, memflags | O_RDWR, 0600);
  if (ipp->fd < 0) {
    error("Error opening shared file: %s: %s\n", SHM_PATH, strerror(errno));
    goto sem_fail;
  }

  if (memflags & O_CREAT) {
    memset(buf, 0, sizeof(buf));
    while (written_len < SHM_SIZ) {
      write(ipp->fd, buf, sizeof(buf));
      written_len += sizeof(buf);
    }
  }
  lseek(ipp->fd, 0, SEEK_SET);

  ipp->shm = mmap(NULL, SHM_SIZ, PROT_READ | PROT_WRITE, MAP_SHARED, ipp->fd, 0);
  if (ipp->shm == MAP_FAILED) {
    error("mmap: %s\n", strerror(errno));
    goto sem_fail;
  }
  close(ipp->fd);
  ipp->dbid = 0;
  return ipp;

 sem_fail:
  //fprintf(log, "FAILURE CONDITION\n");
  free(ipp);
  //fprintf(log, "DONE\n");
/*   SEM_DESTROY(ipp->mutex_caller, "CALLER") */
/*   SEM_DESTROY(ipp->mutex_server, "SERVER") */
/*   SEM_DESTROY(ipp->mutex_reply, "REPLY") */
  // fclose(log);
  return NULL;
}
开发者ID:SoftwareDefinedBuildings,项目名称:BSE,代码行数:63,代码来源:util.c


示例8: main

int main(int argc, char *argv[]) {
    if(argc != 2) {
        fprintf(stderr, "Use this program with the argument 'port'.\n");
        exit(EXIT_FAILURE);
    }
    char *endptr = NULL;
    long int port = strtol(argv[1], &endptr, 10);
    if((port == LONG_MAX || port == LONG_MIN) && errno == ERANGE) {
        perror("strtol");
        exit(EXIT_FAILURE);
    }
    if(argv[1] == endptr) {
        fprintf(stderr, "Error: no digits were found.\n");
        exit(EXIT_FAILURE);
    }
    if(port <= 0 || port > 65535) {
        fprintf(stderr, "Error: %ld isn't a number of port.\n", port);
        exit(EXIT_FAILURE);
    }
    printf("Enter the count of landing planes: ");
    size_t n;
    if(scanf("%lu", &n) < 1) {
        perror("scanf");
        exit(EXIT_FAILURE);
    }
    printf("Enter the number of departing planes: ");
    size_t m;
    if(scanf("%lu", &m) < 1) {
        perror("scanf");
        exit(EXIT_FAILURE);
    }
    printf("Enter the number of strips: ");
    size_t k;
    if(scanf("%lu", &k) < 1) {
        perror("scanf");
        exit(EXIT_FAILURE);
    }
    sem_t **sems;
    sems = (sem_t **)malloc(sizeof(sem_t *) * k);
    if(sems == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    for(size_t i = 0; i < k; ++i) {
        char tmp[25];
        if(snprintf(tmp, 25, SEM_NAME, i) <= 0) {
            perror("snprintf");
            free(sems);
            exit(EXIT_FAILURE);
        }
        if((sems[i] = sem_open(tmp, O_CREAT, 0666, 0)) == SEM_FAILED) {
            perror("sem_open");
            free(sems);
            exit(EXIT_FAILURE);
        }
        while(sem_trywait(sems[i]) == 0) {}
        if(errno != EAGAIN) {
            perror("sem_trywait");
            for(size_t j = i; j > 0; --j) {
                snprintf(tmp, 25, SEM_NAME, j);
                sem_unlink(tmp);
            }
            free(sems);
            exit(EXIT_FAILURE);
        }
        if(sem_post(sems[i]) != 0) {
            perror("sem_open");
            for(size_t j = i; j > 0; --j) {
                snprintf(tmp, 25, SEM_NAME, j);
                sem_unlink(tmp);
            }
            free(sems);
            exit(EXIT_FAILURE);
        }
    }
    struct sockaddr_in servaddr;
    int sockfd, newsockfd;
    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket");
        for(size_t j = 0; j < k; ++j) {
            char tmp[25];
            snprintf(tmp, 25, SEM_NAME, j);
            sem_unlink(tmp);
        }
        free(sems);
        exit(EXIT_FAILURE);
    }
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    if(bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
        perror("bind");
        for(size_t j = 0; j < k; ++j) {
            char tmp[25];
            snprintf(tmp, 25, SEM_NAME, j);
            sem_unlink(tmp);
        }
        free(sems);
        close(sockfd);
//.........这里部分代码省略.........
开发者ID:dem0n-b11,项目名称:Operating_Systems,代码行数:101,代码来源:aeroport.c


示例9: main

int main(int argc, char *argv[])
{
    mutex = sem_open("/mutex", O_CREAT, 0644, 1);
    fillSlots = sem_open("/fillSlots", O_CREAT, 0644, 0);
    emptySlots = sem_open("/emptySlots", O_CREAT, 0644, N);
    
    // Two necessary calls to allocate the shared memory space
    SHM_SIZE = 3 * sizeof(int) + N * sizeof(int);
    shmid = shmget(shmkey, SHM_SIZE, 0666 | IPC_CREAT);  // IPC_CREAT flag to create shared mem
    int *shmpointer = shmat(shmid,NULL,0);  //now attach a memory to this share memory
    if(shmid < 0 || shmpointer == NULL) {
        printf("error allocating shared memory key %d\n", shmkey);
        return -1;
    }
    
    shmpointer[0] = 0;   // in
    shmpointer[1] = 0;   // out
    shmpointer[2] = 1;   // last item produced
    
    printf("*** FactoryShell Usage **** \n");
    printf("FactoryShell> producer 3      (type this to produce 3 items)\n");
    printf("FactoryShell> consumer 4      (type this to consume 4 items,\n");
    printf("                               3 will be consumed and then block)\n");
    printf("Return or end to quit\n");
    
    while(!bEnd) {
        printf("FactoryShell> ");
        fgets(cmd, sizeof(cmd), stdin);
        
        strcpy(arg,"");
        if (strchr(cmd, ' ') != NULL) sscanf(cmd,"%s %s",role,arg);
        else sscanf(cmd,"%s",role);
        if(strcmp(role,"end") == 0 || strcmp(role, "exit")==0) { bEnd = 1; break; }
        
        //fill the args we will pass to the child programs
        getcwd(programpath, 80);
        strcat(programpath, "/");
        strcat(programpath, role);
        args[0] = programpath;
        args[1] = arg;
        args[2] = Nstr;
        args[3] = NULL;
        
        if(strcmp(role,"consumer") == 0 || strcmp(role, "producer") == 0) {
            
            // **********************************************************************
            // Exercice) Add the necessary code here to call the children
            pid = fork();
            if(pid==0) {
                execve(programpath, args, NULL);
            }
            else if(pid<0) {
                printf("Error when forking the program\n");
                bEnd = 1;
            }
        }
        else {
            printf("Command not recognized\n");
            printf("Usage: producer integer  (num of elems to produce)\n");
            printf("       consumer integer  (num of elems to consume)\n\n");
            if(strlen(cmd) == 1) bEnd = 1;
        }
        usleep(1000000);
    }
    
    shmdt(shmpointer);
    shmctl(shmid, IPC_RMID, 0); 
    
    sem_close(mutex);
    sem_close(fillSlots);
    sem_close(emptySlots);
    
    sem_unlink("/mutex");
    sem_unlink("/fillSlots");
    sem_unlink("/emptySlots");
    
    return 0;
}
开发者ID:rhaps0dy,项目名称:os-experiments,代码行数:78,代码来源:Factory.c


示例10: main

int main(int argc, char *argv[])
{
  sem_t *sem_mutex;  //Binary semaphore to use a mutex
  int *stateptr;     //Shared memory global int to store active button state
  int hit_count = 0, rows, cols;
  WINDOW *mainwin = NULL;
  int nextch;
  MEVENT event;
  struct sigaction act;

  //Create a binary semaphore to use as a mutex:
  //(will be inerited by children)
  if ((sem_mutex = sem_open("/mutex", O_CREAT|O_EXCL, 0600, 1)) == SEM_FAILED) {
    perror("Semaphore creation failed");
    return EXIT_FAILURE; }

  //Now unlink semaphore so it will be deleted in case of ^-C or crash:
  sem_unlink("/mutex");

  //Setup anonymous, shared memory for global int:
  if ((stateptr = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0)) == MAP_FAILED) {
    perror("Shared memory creation failed");
    return EXIT_FAILURE; }

  //Initialize button state (no active buttons):
  *stateptr = 0;

  //Initialize and setup the curses window:
  if ((mainwin = initscr()) == NULL) {
    fprintf(stderr,"Failed to initialize curses window\n");
    return EXIT_FAILURE; }
  getmaxyx(mainwin,rows,cols);
  mvprintw(rows/2,cols/2-18,"Click on the Corner Buttons to Score!",rows,cols);
  mvprintw(rows/2+2,cols/2-10,"(rows: %d  cols: %d)",rows,cols);
  refresh();

  //Setup signal handler for SIGCHLD signals:
  memset(&act,0,sizeof(act));
  act.sa_handler = sigchld_handler;
  sigemptyset(&act.sa_mask);
  sigaction(SIGCHLD,&act,NULL);

  //Create children:
  //****************
 
  for (int i=0; i < running; i++){//memory problem???
	  switch(fork()){
		  case -1:
			perror("fork failed");
			sigchld_handler(EXIT_FAILURE);
			endwin();//put this in here since failures don't close the window apparently.
			exit(EXIT_FAILURE);
		  case 0:
			
			child_func(1+i, rows, cols,sem_mutex,stateptr);//1+processcount allows for proper numbering.
			sigchld_handler(EXIT_SUCCESS);
			exit(EXIT_SUCCESS);
		  default: 
		    break;//no break leads to error apparently.
			//I got it now the switch statement will determine the parent function follows the default.
		}
  }

  //Setup curses to get mouse events:
  keypad(mainwin, TRUE);
  mousemask(ALL_MOUSE_EVENTS, NULL);

  //Loop catching mouse clicks while children are running:
    while (running > 0) {
    //nextch = wgetch(mainwin);
    if ((nextch = getch()) == KEY_MOUSE && getmouse(&event) == OK && (event.bstate & BUTTON1_PRESSED)) {
      //Check if user clicked on a label:
      if (check_click(*stateptr, event.x, event.y, rows, cols)) {
        //Clicked on current label:
        hit_count++;
        mvprintw(rows/2+5,cols/2-11,"Got #%d at (%3d,%3d)",*stateptr,event.x,event.y);
        wrefresh(curscr);  //Need this to ensure entire screen is redrawn despite child changes.
      } }
  }

  //Close curses window so terminal settings are restored to normal:
  endwin();

  //Print out results:
  printf("\nYour hit count was: %d\n\n",hit_count);

  //Collect all the children:
  //*************************
  //return exit success if child successfully exited.
  int status;
  int tempcount = 0;//made a temp count since I think running will be 0 by now.
  while(tempcount<4){
  wait(&status);// wait for children shouldn't all return status
 
  if(WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS){
	tempcount++;//increment temp count.
  }else
	exit(EXIT_FAILURE);//return exit failure according to lecture.
  }
  exit(EXIT_SUCCESS);//completes while loop so returns exit success.
//.........这里部分代码省略.........
开发者ID:RyanSample,项目名称:MouseClickerGame,代码行数:101,代码来源:mousegame.c


示例11: main

/* The main test function. */
int main(int argc, char *argv[])
{
	int ret, value;

	sem_t *sem1, *sem2;

	/* Initialize output */
	output_init();

	/* Create the semaphore */
	sem1 = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0777, 1);

	if ((sem1 == SEM_FAILED) && (errno == EEXIST)) {
		sem_unlink(SEM_NAME);
		sem1 = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0777, 1);
	}

	if (sem1 == SEM_FAILED) {
		UNRESOLVED(errno, "Failed to create the semaphore");
	}

	/* Unlink */
	ret = sem_unlink(SEM_NAME);

	if (ret != 0) {
		UNRESOLVED(errno, "Failed to unlink the semaphore");
	}

	/* Try reconnect */
	sem2 = sem_open(SEM_NAME, 0);

	if (sem2 != SEM_FAILED) {
		FAILED("Reconnecting the unlinked semaphore did not failed");
	}

	if (errno != ENOENT) {
		output("Error %d: %s\n", errno, strerror(errno));
		FAILED
		    ("Reconnecting the unlinked semaphore failed with a wrong error");
	}

	/* Reopen the semaphore */
	sem2 = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0777, 3);

	if (sem2 == SEM_FAILED) {
		output("Gor error %d: %s\n", errno, strerror(errno));
		FAILED("Failed to recreate the semaphore");
	}

	/* Check the semaphore have different values */
	ret = sem_getvalue(sem1, &value);

	if (ret != 0) {
		UNRESOLVED(errno, "Failed to read sem1 value");
	}

	if (value != 1) {
		output("Read: %d\n", value);
		FAILED("Semaphore value is not as expected");
	}

	ret = sem_getvalue(sem2, &value);

	if (ret != 0) {
		UNRESOLVED(errno, "Failed to read sem1 value");
	}

	if (value != 3) {
		output("Read: %d\n", value);
		FAILED("Semaphore value is not as expected");
	}

	/* Unlink */
	ret = sem_unlink(SEM_NAME);

	if (ret != 0) {
		UNRESOLVED(errno, "Failed to unlink the semaphore");
	}

	/* close both */
	ret = sem_close(sem1);

	if (ret != 0) {
		UNRESOLVED(errno, "Failed to close the semaphore");
	}

	ret = sem_close(sem2);

	if (ret != 0) {
		UNRESOLVED(errno, "Failed to close the semaphore");
	}

	/* Test passed */
#if VERBOSE > 0
	output("Test passed\n");

#endif
	PASSED;
}
开发者ID:Nan619,项目名称:ltp-ddt,代码行数:100,代码来源:6-1.c


示例12: mca_sharedfp_sm_file_open


//.........这里部分代码省略.........
    /* the semaphore is shared by keeping it in the shared memory segment  */

#ifdef OMPIO_SHAREDFP_USE_UNNAMED_SEMAPHORES
    if(sem_init(&sm_offset_ptr->mutex, 1, 1) != -1){
#else
    sm_data->sem_name = (char*) malloc( sizeof(char) * (strlen(filename_basename)+32) );
    sprintf(sm_data->sem_name,"OMPIO_sharedfp_sem_%s",filename_basename);

    if( (sm_data->mutex = sem_open(sm_data->sem_name, O_CREAT, 0644, 1)) != SEM_FAILED ) {
#endif
	/*If opening was successful*/
	/*Store the new file handle*/
	sm_data->sm_offset_ptr = sm_offset_ptr;
	/* Assign the sm_data to sh->selected_module_data*/
	sh->selected_module_data   = sm_data;
	/*remember the shared file handle*/
	fh->f_sharedfp_data = sh;

	/*write initial zero*/
	if(rank==0){
	    MPI_Offset position=0;

#ifdef OMPIO_SHAREDFP_USE_UNNAMED_SEMAPHORES
	    sem_wait(sm_offset_ptr->mutex);
	    sm_offset_ptr->offset=position;
	    sem_post(sm_offset_ptr->mutex);
#else
	    sem_wait(sm_data->mutex);
	    sm_offset_ptr->offset=position;
	    sem_post(sm_data->mutex);
#endif
	}
    }else{
        free(sm_filename);
	free(sm_data);
	free(sh);
	free(shfileHandle);
        munmap(sm_offset_ptr, sizeof(struct sm_offset));
	err = OMPI_ERROR;
    }

    comm->c_coll.coll_barrier (comm, comm->c_coll.coll_barrier_module );

    return err;
}

int mca_sharedfp_sm_file_close (mca_io_ompio_file_t *fh)
{
    int err = OMPI_SUCCESS;
    /*sharedfp data structure*/
    struct mca_sharedfp_base_data_t *sh=NULL;
    /*sharedfp sm module data structure*/
    struct mca_sharedfp_sm_data * file_data=NULL;

    if( NULL == fh->f_sharedfp_data ){
	if ( mca_sharedfp_sm_verbose ) {
	    printf("sharedfp_sm_file_close: shared file pointer structure not initialized\n");
	}
        return OMPI_SUCCESS;
    }
    sh = fh->f_sharedfp_data;

    /* Use an MPI Barrier in order to make sure that
     * all processes are ready to release the
     * shared file pointer resources
     */
    sh->comm->c_coll.coll_barrier (sh->comm, sh->comm->c_coll.coll_barrier_module );

    file_data = (sm_data*)(sh->selected_module_data);
    if (file_data)  {
        /*Close sm handle*/
        if (file_data->sm_offset_ptr) {
            /* destroy semaphore */
#ifdef OMPIO_SHAREDFP_USE_UNNAMED_SEMAPHORES
	    sem_destroy(file_data->sm_offset_ptr->mutex);
#else
 	    sem_unlink (file_data->sem_name);
 	    free (file_data->sem_name);
#endif
            /*Release the shared memory segment.*/
            munmap(file_data->sm_offset_ptr,sizeof(struct sm_offset));
            /*Q: Do we need to delete the file? */
            remove(file_data->sm_filename);
        }
        /*free our sm data structure*/
        if(file_data->sm_filename){
            free(file_data->sm_filename);
        }
        free(file_data);
    }

    /* Close the main file opened by this component*/
    err = ompio_io_ompio_file_close(sh->sharedfh);

    /*free shared file pointer data struct*/
    free(sh);

    return err;

}
开发者ID:XuanWang1982,项目名称:ompi,代码行数:101,代码来源:sharedfp_sm_file_open.c


示例13: main

/* The main test function. */
int main(void)
{
	int ret, i;
	char *name = "/sem_open_15_1";

	sem_t *sems[4];

	/* Initialize output */
	output_init();

	/* Initialize all semaphores */

	for (i = 0; i < 4; i++) {
		sems[i] = sem_open(name, O_CREAT, 0777, 1);

		if (sems[i] == SEM_FAILED) {
			UNRESOLVED(errno, "Failed to sem_open");
		}

	}

	/* Check all calls returned the same @ */
	for (i = 0; i < 3; i++) {
		if (sems[i] != sems[i + 1]) {
			FAILED("sem_open returned a different address");
		}

		/* Close some semaphores */
		ret = sem_close(sems[i]);

		if (ret != 0) {
			UNRESOLVED(errno, "Failed to sem_close");
		}
	}

	/* Now, reopen, we should still get the same address */
	for (i = 0; i < 3; i++) {
		sems[i] = sem_open(name, O_CREAT, 0777, 1);

		if (sems[i] == SEM_FAILED) {
			UNRESOLVED(errno, "Failed to sem_open");
		}

	}

	/* Check all calls returned the same @ */
	for (i = 0; i < 3; i++) {
		if (sems[i] != sems[i + 1]) {
			FAILED("sem_open returned a different address");
		}
	}

	/* Close all semaphores */
	for (i = 0; i < 4; i++) {
		ret = sem_close(sems[i]);

		if (ret != 0) {
			UNRESOLVED(errno, "Failed to sem_close");
		}
	}

	sem_unlink(name);

	/* Test passed */
#if VERBOSE > 0

	output("Test passed\n");

#endif

	PASSED;
}
开发者ID:kraj,项目名称:ltp,代码行数:73,代码来源:15-1.c


示例14: main

int main(){

char *array;
int fd;
sem_t *sema_n;
 int ret,val;
 
printf("%s : Im start \n", MYNAME);

char pathname[] = "lab901.c";

/* Получаем дескриптор общей памяти */
  sem_getvalue(sema_n, &val);
  printf("semaphore value = %d\n", val);
  
  if ((shm_fd = shm_open("my_shm", O_CREAT | O_RDWR, 0666)) ==
                                                          -1){
    perror("cannot open");
    return -1;
  }
 
  /* Устанавливаем размер общей памяти равным SHM_SIZE */
  if (ftruncate(shm_fd, SHM_SIZE) != 0){
    perror("cannot set size");
    return -1;
  }
 
  /*
   * Подключаем общую память в адресное пространство. Флаг
   * MAP_SHARED говорит, что это подключение общей памяти.
   */
  if ((array = (char *) mmap(0, SHM_SIZE, PROT_WRITE, MAP_SHARED,
               shm_fd, 0)) == MAP_FAILED){
    perror("cannot mmap");
    return -1;
  }
  sem_wait(sema_n);
  /* Блокируем общую память. Не забываем про этот шаг */
  if (mlock(vaddr, SHM_SIZE) != 0){
    perror("cannot mlock");
    return -1;
  }

int i;
i = 0;
printf("%s : code in lab901.c:\n", MYNAME);
printf("-----------------------------------------------------------\n\n");

while (array[i] != EOF ){
        
        putchar(array[i]);
        ++i;
}
printf("%s \n", array);
if (sem_post(sema_n) != 0)
    perror("post error");
munmap(vaddr, SHM_SIZE);

sem_close(sema_n);
sem_unlink(SEM_NAME);

close(shm_fd);
shm_unlink("my_shm");

printf("%s : \nAll shared mamory released\n\n", MYNAME);

return 0;

} 
开发者ID:sergeiignatov,项目名称:os-course-2013,代码行数:69,代码来源:lab902.c


示例15: TEST_BEGIN


//.........这里部分代码省略.........
  puts( "Init: sem_open - Open new sem without create flag (ENOENT)" );
  n_sem2 = sem_open("sem3", O_EXCL, 0777, 1);
  fatal_posix_sem( n_sem2, "sem_open error return status" );
  fatal_posix_service_status( errno, ENOENT,  "sem_open errno EEXIST");

  /*
   * XXX - Could not hit the following errors:
   *   E_POSIX_Semaphore_Create_support only fails if
   *     ENOSYS - When semaphore is shared between processes.
   *     ENOSPC - When out of memory.
   */

  /*
   * Validate we can wait on a semaphore opened with sem_open.
   */

  puts( "Init: sem_wait on sem1" );
  status = sem_wait(n_sem1);
  fatal_posix_service_status( status, 0, "sem_wait opened semaphore");

  /*
   * Validate a second open returns the same semaphore.
   */

  puts( "Init: sem_open - Open an existing sem ( same id )" );
  n_sem2 = sem_open("sem1", 0 );
  rtems_test_assert( n_sem2 == n_sem1 );

  /*
   * Unlink the semaphore, then verify an open of the same name produces a
   * different semaphore.
   */

  puts( "Init: sem_unlink - sem1 SUCCESSFUL" );
  status = sem_unlink( "sem1" );
  fatal_posix_service_status( status, 0, "sem_unlink locked semaphore");

  puts( "Init: sem_open - Reopen sem1 SUCCESSFUL with a different id" );
  n_sem2 = sem_open( "sem1", O_CREAT | O_EXCL, 0777, 1);
  rtems_test_assert( n_sem2 != SEM_FAILED );
  rtems_test_assert( n_sem2 != n_sem1 );

  /*
   * Validate we can call close on a semaphore opened with sem_open.
   */

  puts( "Init: sem_close (1) - SUCCESSFUL" );
  status = sem_close( n_sem1 );
  fatal_posix_service_status( status, 0, "sem_close semaphore");

  /*
   * Validate it n_sem2 (the last open for sem1 name can be
   * correctly closed and unlinked.
   */

  puts( "Init: sem_close (2) - SUCCESSFUL" );
  status = sem_close( n_sem2 );
  fatal_posix_service_status( status, 0, "sem_close semaphore");

  puts( "Init: sem_unlink - sem1 (2) SUCCESSFUL" );
  status = sem_unlink( "sem1" );
  fatal_posix_service_status( status, 0, "sem_unlink locked semaphore");

  puts( "Init: sem_close - UNSUCCESSFUL (EINVAL)" );
  status = sem_close(n_sem2);
  fatal_posix_service_status( status, -1, "sem_close error return status");
开发者ID:AlexShiLucky,项目名称:rtems,代码行数:67,代码来源:init.c


示例16: shm_unlink

/** Cleanup existing shared memory segments.
 * @param name shared memory segment name
 */
void
SharedMemoryRegistry::cleanup(const char *name)
{
  shm_unlink(name ? name : DEFAULT_SHM_NAME);
  sem_unlink(name ? name : DEFAULT_SHM_NAME);
}
开发者ID:sanyaade-teachings,项目名称:fawkes,代码行数:9,代码来源:shm_registry.cpp


示例17: timesynckcal_exit

//------------------------------------------------------------------------------
void timesynckcal_exit(void)
{
    sem_close(syncSem_l);
    sem_unlink(TIMESYNC_SYNC_BSDSEM);
}
开发者ID:chutao,项目名称:openPOWERLINK_V2,代码行数:6,代码来源:timesynckcal-bsdsem.c


示例18: strdup

/** Constructor.
 * @param name name of the shared memory region. Must follow the rules
 * set by shm_open(). If NULL defaults to "/fawkes-shmem-registry".
 */
SharedMemoryRegistry::SharedMemoryRegistry(const char *name)
{
  __shm_name = name ? strdup(name) : strdup(DEFAULT_SHM_NAME);

  __sem = sem_open(__shm_name, O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP, 1);

  if (__sem == SEM_FAILED) {
    free(__shm_name);
    throw Exception(errno, "Failed to init shared memory registry semaphore");
  }

  sem_wait(__sem);

  __shmfd = shm_open(__shm_name, O_RDWR | O_CREAT | O_EXCL,
                     S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);

  bool created = false;

  if ((__shmfd < 0) && (errno == EEXIST)) {
    __shmfd = shm_open(__shm_name, O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
  } else {
    if (ftruncate(__shmfd, sizeof(MemInfo)) != 0) {
      close(__shmfd);
      shm_unlink(__shm_name);
      sem_post(__sem);
      sem_close(__sem);
      sem_unlink(__shm_name);
      free(__shm_name);
      throw Exception(errno, "Failed to resize memory for shared memory registry");
    }

    created = true;
  }

  if (__shmfd < 0) {
    sem_post(__sem);
    sem_close(__sem);
    sem_unlink(__shm_name);
    free(__shm_name);
    throw Exception(errno, "Failed to open shared memory registry");
  }

  __meminfo = (MemInfo *)mmap(NULL, sizeof(MemInfo), PROT_READ | PROT_WRITE,
			      MAP_SHARED, __shmfd, 0);
  if (__meminfo == MAP_FAILED) {
    close(__shmfd);
    sem_close(__sem);
    free(__shm_name);
    throw Exception(errno, "Failed to mmap shared memory registry");
  }

  if (created) {
    memset(__meminfo, 0, sizeof(MemInfo));
  
    for (unsigned int i = 0; i < MAXNUM_SHM_SEGMS; ++i) {
      __meminfo->segments[i].shmid = -1;
    }
  }

  __master   = created;

  sem_post(__sem);
}
开发者ID:sanyaade-teachings,项目名称:fawkes,代码行数:67,代码来源:shm_registry.cpp


示例19: main


//.........这里部分代码省略.........
		free(config.out_dev);
	}
	
	printf("Device %d deinitialized py process %d\n", config.idevice, pid);

	// On master process perform results check:
	// compare each GPU result to CPU result.
	if (master)
	{
		float* control = inout + np * ndevices;
		for (int idevice = 0; idevice < ndevices; idevice++)
		{
			// Find the maximum abs difference.
			int maxi = 0, maxj = 0;
			float maxdiff = fabs(control[0] - (inout + idevice * np)[0]);
			for (int j = 0; j < ny; j++)
			{
				for (int i = 0; i < nx; i++)
				{
					float diff = fabs(
						control[i + j * nx] -
						(inout + idevice * np)[i + j * nx]);
					if (diff > maxdiff)
					{
						maxdiff = diff;
						maxi = i; maxj = j;
					}
				}
			}
			printf("Device %d result abs max diff = %f @ (%d,%d)\n",
				idevice, maxdiff, maxi, maxj);
		}
	}
	
	// Unlink semaphore.
	if (master)
	{
		int sem_status = sem_unlink("/shmem_mmap_cuda_sem1");
		if (sem_status == -1)
		{
			fprintf(stderr, "Cannot unlink semaphore #1 by process %d, errno = %d\n",
				pid, errno);
			return errno;
		}
	}
	
	// Close semaphore.
	int sem_status = sem_close(sem1);
	if (sem_status == -1)
	{
		fprintf(stderr, "Cannot close semaphore #1 by process %d, errno = %d\n",
			pid, errno);
		return errno;
	}

	// Unlink semaphore.
	if (master)
	{
		int sem_status = sem_unlink("/shmem_mmap_cuda_sem2");
		if (sem_status == -1)
		{
			fprintf(stderr, "Cannot unlink semaphore #2 by process %d, errno = %d\n",
				pid, errno);
			return errno;
		}
	}
	
	// Close semaphore.
	sem_status = sem_close(sem2);
	if (sem_status == -1)
	{
		fprintf(stderr, "Cannot close semaphore #2 by process %d, errno = %d\n",
			pid, errno);
		return errno;
	}

	// Unmap shared region.
	close(fd);
	int munmap_status = munmap(inout, size * (ndevices + 1));
	if (munmap_status == -1)
	{
		fprintf(stderr, "Cannot unmap shared region by process %d, errno = %d\n",
			pid, errno);
		return errno;
	}
	
	// Unlink shared region.
	if (master)
	{
		int unlink_status = shm_unlink("/shmem_mmap_cuda_shm");
		if (unlink_status == -1)
		{
			fprintf(stderr, "Cannot unlink shared region by process %d, errno = %d\n",
				pid, errno);
			return errno;
		}
	}
	
	return 0;
}
开发者ID:7633,项目名称:msu-cuda-course,代码行数:101,代码来源:shmem_mmap_cuda.c


示例20: main


//.........这里部分代码省略.........
	{
		printf("Fail to create timer thread2!");
		flushall();
	}
	else
	{
		printf("The timer thread2 ID is %i \n",timerThreadID);
		flushall();
	}
//
//----start the block Identification thread-----------------
//	pFile = fopen("Blocks.txt","w+");
	pthread_create(&blockIDThreadID,&attr,blockID,NULL);
		if(blockIDThreadID == -1)
	{
		printf("Fail to create block indeptification thread!");
		flushall();
	}
	else
	{
		printf("The BlockID's thread ID is %i \n",blockIDThreadID);
		flushall();
	}
	delay(10);
//---------------------keyboard thread------------------------
	pthread_create(&keyboardThreadID,&attr,keyboard_input,NULL);
		if(keyboardThreadID == -1)
	{
		printf("Fail to create keyboard input!");
		flushall();
	}
	else
	{
		printf("The keyboard_input ID is %i \n",timerThreadID);
		flushall();
	}
	delay(10);
//----------------GUI Monitor Thread---------------------
	pthread_create(NULL,&attr,GUI_thread,NULL);
	delay(10);
// --------------------SIM pulse Handler Loop Thread----------
	pthread_create(NULL,&attr,Handlerloop_thread,NULL);
	delay(10);
// --------------------SIM Monitor Thread---------------------
	pthread_create(NULL,&attr,SIM_thread,NULL);
	delay(10);
// --------------------Auto mode thread-----------------------
	pthread_create(NULL,&attr,auto_thread,NULL);
	delay(10);
// --------------------others---------------------------------
	// call mainLoop()
	mainLoop();
	// sleep for 10sec
	printf("Sleep the program for 10 seconds\n");
	flushall;
	sleep(10);
	// start release system resourse
	printf("Clean up and release system resourse\n");
	flushall;
	// Kill the existing processes
	kill_gui = kill(pid_gui, 0);
	kill_sim = kill(pid_sim, 0);
	kill_pport = kill(pid_pport, 0);
    if (kill_gui == -1)
	{
		printf("GUI Kill failed\n");
		flushall();
	}
	if (kill_sim == -1)
	{
		printf("SIM Kill failed\n");
		flushall();
	} 
	if (kill_pport == -1)
	{
		printf("PPort Kill failed\n");
		flushall();
	}
	// Close and unlink Semo 

鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C++ sem_v函数代码示例发布时间:2022-05-30
下一篇:
C++ sem_trywait函数代码示例发布时间: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