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

C++ sem_close函数代码示例

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

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



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

示例1: main

int main() {

    VolumeManager *vm;
    CommandListener *cl;
    NetlinkManager *nm;

    SLOGI("Vold 2.1 (the revenge) firing up");

    mkdir("/dev/block/vold", 0755);
	udisk_sem=sem_open("vold_sem",1);
    /* Create our singleton managers */
    if (!(vm = VolumeManager::Instance())) {
        SLOGE("Unable to create VolumeManager");
        exit(1);
    };

    if (!(nm = NetlinkManager::Instance())) {
        SLOGE("Unable to create NetlinkManager");
        exit(1);
    };


    cl = new CommandListener();
    vm->setBroadcaster((SocketListener *) cl);
    nm->setBroadcaster((SocketListener *) cl);

    if (vm->start()) {
        SLOGE("Unable to start VolumeManager (%s)", strerror(errno));
        exit(1);
    }

    if (process_config(vm)) {
        SLOGE("Error reading configuration (%s)... continuing anyways", strerror(errno));
    }

    if (nm->start()) {
        SLOGE("Unable to start NetlinkManager (%s)", strerror(errno));
        exit(1);
    }

    coldboot("/sys/block");
//    coldboot("/sys/class/switch");

    /*
     * Now that we're up, we can respond to commands
     */
    if (cl->startListener()) {
        SLOGE("Unable to start CommandListener (%s)", strerror(errno));
        exit(1);
    }

    // Eventually we'll become the monitoring thread
    while(1) {
        sleep(1000);
    }

	sem_close(udisk_sem);

	sem_unlink("vold_sem");

    SLOGI("Vold exiting");
    exit(0);
}
开发者ID:xwaynec,项目名称:Vixen-system,代码行数:63,代码来源:main.cpp


示例2: main

/* The main test function. */
int main(int argc, char *argv[])
{
	int ret, status;
	pid_t child, ctl;
	sem_t *sem;
	struct timespec tsini, tsfin;

	/* Initialize output */
	output_init();

	/* read current time */
	ret = clock_gettime(CLOCK_REALTIME, &tsini);
	if (ret == -1)
		UNRESOLVED(errno, "Unable to read CLOCK_REALTIME clock");

	/* Set temporary value in tsfin for semaphore timeout */
	tsfin.tv_sec = tsini.tv_sec + 3;
	tsfin.tv_nsec = tsini.tv_nsec;

	/* Create the child */
	child = fork();
	if (child == -1)
		UNRESOLVED(errno, "Failed to fork");

	/* Open the semaphore */
	sem = sem_open(SEM_NAME, O_CREAT, O_RDWR, 0);
	if (sem == SEM_FAILED)
		UNRESOLVED(errno, "Failed to open the semaphore (try executing "
			   "as root)");

	/* sleep 1 second */
	sleep(1);

	/* child posts the semaphore and terminates */
	if (child == 0) {
		do {
			ret = sem_post(sem);
		} while (ret == -1 && errno == EINTR);

		if (ret == -1)
			UNRESOLVED(errno, "Failed to post the semaphore");

		ret = sem_close(sem);
		if (ret == -1)
			UNRESOLVED(errno, "Failed to close the semaphore");

		/* The child stops here */
		exit(0);
	}

	/* Parent waits for the semaphore */
	do {
		ret = sem_timedwait(sem, &tsfin);
	} while (ret == -1 && errno == EINTR);

	if (ret == -1) {
		if (errno == ETIMEDOUT)
			FAILED("The new process does not execute");
		UNRESOLVED(errno, "Failed to wait for the semaphore");
	}

	/* We don't need the semaphore anymore */
	ret = sem_close(sem);
	if (ret == -1)
		UNRESOLVED(errno, "Failed to close the semaphore");

	ret = sem_unlink(SEM_NAME);
	if (ret == -1)
		UNRESOLVED(errno, "Unable to unlink the semaphore");

	/* Parent joins the child */
	ctl = waitpid(child, &status, 0);
	if (ctl != child)
		UNRESOLVED(errno, "Waitpid returned the wrong PID");

	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
		UNRESOLVED(status, "Child exited abnormally");

	/* Check the global duration */
	ret = clock_gettime(CLOCK_REALTIME, &tsfin);
	if (ret == -1)
		UNRESOLVED(errno, "Unable to read CLOCK_REALTIME clock");

	if (tsfin.tv_nsec < tsini.tv_nsec)
		tsfin.tv_sec -= 1;

	status = tsfin.tv_sec - tsini.tv_sec;
	if (status >= 2) {
		/* the operation was more than 2 secs long */
		FAILED("the processes did not execute concurrently");
	}

	output("Test passed\n");

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


示例3: sem_unlink

int sem_unlink(FAR const char *name)
{
  FAR struct inode *inode;
  FAR const char *relpath = NULL;
  char fullpath[MAX_SEMPATH];
  int errcode;
  int ret;

  /* Get the full path to the semaphore */

  snprintf(fullpath, MAX_SEMPATH, CONFIG_FS_NAMED_SEMPATH "/%s", name);

  /* Get the inode for this semaphore. */

  sched_lock();
  inode = inode_find(fullpath, &relpath);
  if (!inode)
    {
      /* There is no inode that includes in this path */

      errcode = ENOENT;
      goto errout;
    }

  /* Verify that what we found is, indeed, a semaphore */

  if (!INODE_IS_NAMEDSEM(inode))
    {
      errcode = ENXIO;
      goto errout_with_inode;
    }

  /* Refuse to unlink the inode if it has children.  I.e., if it is
   * functioning as a directory and the directory is not empty.
   */

  inode_semtake();
  if (inode->i_child != NULL)
    {
      errcode = ENOTEMPTY;
      goto errout_with_semaphore;
    }

  /* Remove the old inode from the tree.  Because we hold a reference count
   * on the inode, it will not be deleted now.  This will set the
   * FSNODEFLAG_DELETED bit in the inode flags.
   */

  ret = inode_remove(fullpath);

  /* inode_remove() should always fail with -EBUSY because we hae a reference
   * on the inode.  -EBUSY means taht the inode was, indeed, unlinked but
   * thatis could not be freed because there are refrences.
   */

  DEBUGASSERT(ret >= 0 || ret == -EBUSY);
  UNUSED(ret);

  /* Now we do not release the reference count in the normal way (by calling
   * inode release.  Rather, we call sem_close().  sem_close will decrement
   * the reference count on the inode.  But it will also free the semaphore
   * if that reference count decrements to zero.  Since we hold one reference,
   * that can only occur if the semaphore is not in-use.
   */

  inode_semgive();
  ret = sem_close((FAR sem_t *)inode->u.i_nsem);
  sched_unlock();
  return ret;

errout_with_semaphore:
  inode_semgive();
errout_with_inode:
  inode_release(inode);
errout:
  set_errno(errcode);
  sched_unlock();
  return ERROR;
}
开发者ID:justdoitding,项目名称:Nuttx_PSoC4,代码行数:79,代码来源:sem_unlink.c


示例4: create_server

void create_server(void)
{
	int status;
	int sd[MAX_PORT];
	int addrlen;
	const unsigned short int port[] = {0x9234, 0x9235, 0x9236, 0x9237}; 
	struct sockaddr_in sin[MAX_PORT];
	int fd1; 
	int j = 0;
	int i = 0;
	pid_t child_id[4];
//	struct timeval timeout;
	pid_t parent_id = getpid();
	sem_t *mutex;
	fd_set read_fd_set;
	fd_set pipe_fd_set; /* pipe set */
	int pd[MAX_PORT][2]; /* pipes */
	char buf[MAX_PORT];
	int count = 0;

	fd1 = open ("/tmp/whatever.txt", O_CREAT |  O_RDWR | O_TRUNC, 0644);

//	timeout.tv_sec  = 1 * 60;
//	timeout.tv_usec = 0;

	/* Initialize the set of active sockets. */
	FD_ZERO (&read_fd_set);
	FD_ZERO (&pipe_fd_set);


	mutex = sem_open(SEM_NAME, O_CREAT, 0644, 1);
	if(mutex == SEM_FAILED)
	{
		log_stuff("unable to create semaphore",errno);
		sem_unlink(SEM_NAME);
		exit(EXIT_FAILURE);
	}

	system("echo begin > /tmp/error.txt"); 

	for(; j < MAX_PORT; j++) {

		populate_sock(&sd[j],&sin[j], port[j]);
		if(pipe(pd[j]) == -1) {
			log_stuff(strerror(errno), __LINE__);
			exit(EXIT_FAILURE);		
		}
//		fcntl(sd[j], F_SETFL, O_NONBLOCK);
		log_stuff("filedesc we get=", sd[j]);
		FD_SET (sd[j], &read_fd_set);
		FD_SET (pd[j][0], &pipe_fd_set); /* */
		child_here(read_fd_set, fd1, mutex, pd[j][1]);/* */
	}


	if(getpid() == parent_id) {
		parent_stuff(pipe_fd_set, fd1, mutex);
	}

	log_stuff("after waitpid line=", getpid());
	close(fd1);
	sem_close(mutex);
	sem_unlink(SEM_NAME);
	exit(EXIT_FAILURE);
}
开发者ID:initpidzero,项目名称:example_code,代码行数:65,代码来源:udp_pipe.c


示例5: main

/* The main test function. */
int main( int argc, char * argv[] )
{
	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:SummerSnail2014,项目名称:haiku,代码行数:85,代码来源:15-1.c


示例6: startServer

void startServer(int portnum){

	struct sockaddr_in clientAddr; // client socket informations
	socklen_t clientAddrLen; // client socket address length

	// initialize size of struct
	clientAddrLen = sizeof(struct sockaddr_in);

	//clear junk values
	memset(&clientAddr,0,clientAddrLen);

	if((gI_socketFd = initializeSocket(portnum))==-1){
		perror("Initialize socket");
		return;
	}

	fprintf(stderr,"[%ld]MainServer initialized socket\n",(long)gPid_server);

	// create a semafor to control writing sequential to pipe
	sem_unlink(PIPE_CONTROL_SEM);
	getnamed(PIPE_CONTROL_SEM,&gSemP_pipeSem,1); 

	pipe(gPipe_cwpr);
	pipe(gPipe_crpw);
	// TODO : check pipe errors

	pthread_t th_pipeListener;
	pthread_create(&th_pipeListener,NULL,listenPipe,NULL);

	memset(&serverList,0,sizeof(hmlist_t)); //clear junks
	gettimeofday(&endTime,NULL);
	diffTime = getTimeDif(startTime,endTime);
	printf("[%ld]MainServer is builded in %ld ms\n",(long)gPid_server,diffTime);

	hmServData_t miniServer;
	
	pid_t pidChild=-1;
	pid_t pidClient=-1;

	while(!doneflag){

		printf("[%ld]MainServer waiting for clients...\n",(long)gPid_server);
		// accept clients
		fdClient = accept(gI_socketFd,(struct sockaddr*)&clientAddr,&clientAddrLen);
		if(fdClient !=-1 && !doneflag){
			// client send pid address and server creates new mini server to serv
			read(fdClient,&pidClient,sizeof(pid_t));
			if( (pidChild = fork())==-1){
				perror("Fork");
				doneflag=1;
			}else if(pidChild==0){ // child here
				break;
			}else{ // parent here
				// pair server-client informations
				memset(&miniServer,0,sizeof(hmServData_t));
				miniServer.pidServer=pidChild;
				miniServer.pidClient=pidClient;
				miniServer.fdSocket = fdClient;
				addList(&serverList,&miniServer); // store child informations
				gettimeofday(&endTime,NULL);
				diffTime = getTimeDif(startTime,endTime);
				printf("Client[%ld] connected to server[%ld] in %ld ms\n",
	 									(long)pidClient,(long)pidChild,diffTime);
			}
		}else doneflag=1;
	}

	if(pidChild ==0){ // child here
		// no need to re-open semafor because we forked all memory
		/*sem_close(gSemP_pipeSem);
		getnamed(PIPE_CONTROL_SEM,&gSemP_pipeSem,1);*/
		gPid_server = getpid(); // assing new mini server pid
		deleteList(&serverList); // remove parent values
		startMiniServer(pidClient); // start server
		pthread_join(th_pipeListener,NULL);
		sem_close(gSemP_pipeSem);
		close(gI_socketFd); // close spesific socket fildes
		// return main and close mini server
	}else{ // main server here
		killAllChilds(SIGINT); 
		close(gPipe_cwpr[1]); //close pipe to kill thread

		while(wait(NULL)!=-1){} // wait childs
		// TODO : create thread to wait childs
		deleteList(&serverList);
		printf("[%ld]MainServer Waiting for threads\n",(long)gPid_server);
		pthread_join(th_pipeListener,NULL);
		sem_close(gSemP_pipeSem);
		close(gI_socketFd);
	}
}
开发者ID:hmenn,项目名称:FTP-Server,代码行数:91,代码来源:serv.c


示例7: close_sem

int close_sem(sem_t* handle)
{
	return sem_close(handle);
}
开发者ID:SeanWang26,项目名称:sem-shm-ipc,代码行数:4,代码来源:sem.c


示例8: puts


//.........这里部分代码省略.........
     *   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");
    fatal_posix_service_status( errno, EINVAL, "sem_close errno EINVAL");

    puts( "Init: sem_unlink - UNSUCCESSFUL (ENOENT)" );
    status = sem_unlink("sem1");
    fatal_posix_service_status( status, -1, "sem_unlink error return status");
    fatal_posix_service_status( errno, ENOENT, "sem_close errno EINVAL");


    /*
     * Validate we can unlink (2)
     */

    puts( "Init: sem_unlink (NULL) - EINVAL" );
    status = sem_unlink( NULL );
    fatal_posix_service_status( status, -1, "sem_unlink error return status");
    fatal_posix_service_status( errno, EINVAL, "sem_unlink errno value");

    puts( "Init: sem_unlink (\"\") - EINVAL" );
    status = sem_unlink( "" );
    fatal_posix_service_status( status, -1, "sem_unlink error return status");
    fatal_posix_service_status( errno, EINVAL, "sem_unlink errno value");

    /*
     * XXX - Cant' create location OBJECTS_ERROR or OBJECTS_REMOTE.
     *       sem_close and sem_unlink.
     */

    puts( "Init: sem_unlink - UNSUCCESSFUL (ENOENT)" );
    status = sem_unlink("sem2");
    fatal_posix_service_status( status, -1, "sem_unlink error return status");
    fatal_posix_service_status( errno, ENOENT, "sem_unlink errno ENOENT");
    rtems_test_assert(  (status == -1) && (errno == ENOENT) );


    /* Try adding in unlinking before closing... (can we still open?) */

    puts( "*** END OF POSIX SEMAPHORE MANAGER TEST 1 ***" );
    rtems_test_exit(0);

    return NULL; /* just so the compiler thinks we returned something */
}
开发者ID:FullMentalPanic,项目名称:RTEMS_NEW_TOOL_CHAIN,代码行数:101,代码来源:init.c


示例9: main

int main(int argc, char** argv)
{
    shm_unlink("SHARED_MEMORY_NAME");

    sem_unlink("EMPTY_BUF_SEMAPHORE_NAME");
    sem_unlink("FULL_BUF_SEMAPHORE_NAME");
    sem_unlink("MUTEX_SEMAPHORE_NAME");

    // Создаем разделяемую память для хранения данных
    int shm_buf = shm_open("SHARED_MEMORY_NAME", O_CREAT | O_RDWR, 0777);
    if(shm_buf == -1)
    {
        perror("shm_create");
        return -1;
    }

    int ftr_buf = ftruncate(shm_buf, SHARED_MEMORY_SIZE);
    if(ftr_buf == -1)
    {
        perror("truncate");
        return -1;
    }

    // Общий размер буфера для записи
    int size = SHARED_MEMORY_SIZE / sizeof(int);

    // Создаем семафоры для исключения записи в переполненный буфер,
    // для считывания из пустого буфера и для взаимоисключения
    sem_t* empty_buf_sem = sem_open("EMPTY_BUF_SEMAPHORE_NAME", O_CREAT, 0777, size);
    sem_t* full_buf_sem = sem_open("FULL_BUF_SEMAPHORE_NAME", O_CREAT, 0777, 0);
    sem_t* mutex_sem = sem_open("MUTEX_SEMAPHORE_NAME", O_CREAT, 0777, 1);

    close(shm_buf);

    sem_close(empty_buf_sem);
    sem_close(full_buf_sem);
    sem_close(mutex_sem);

//-------------------------------------------------------------------------------------

    int process = fork();

    // Дочерний процесс (запись)
    if(process == 0)
    {
        // Открываем семафоры
        sem_t* empty_buf_sem = sem_open("EMPTY_BUF_SEMAPHORE_NAME", 0, 0777, size);
        sem_t* full_buf_sem = sem_open("FULL_BUF_SEMAPHORE_NAME", 0, 0777, 0);
        sem_t* mutex_sem = sem_open("MUTEX_SEMAPHORE_NAME", 0, 0777, 1);

        // Открываем разделяемую память
        int shm_buf = shm_open("SHARED_MEMORY_NAME", O_RDWR, 0777);
        if(shm_buf == 1)
        {
            perror("shm_open");
            return -1;
        }

        // Отображаем память
        void* addr = mmap(0, SHARED_MEMORY_SIZE, PROT_WRITE | PROT_READ, MAP_SHARED, shm_buf, 0);

        //--------------------------------------------------------------------------------------

        // Генерируем числа и записываем их в разделяемую память
        int i = 0;
        int number;

        void* TempBuf = malloc(sizeof(int));

        srand(time(NULL));

        for(i = 0; i < size; ++i)
        {
            number = 1 + rand() % 100;
            printf("write: %d\n", number);

            sem_wait(empty_buf_sem);
            sem_wait(mutex_sem);

            sprintf(TempBuf, "%d", number);
            memcpy( (int*)addr + i, (int*)TempBuf, sizeof(int) );

            sem_post(mutex_sem);
            sem_post(full_buf_sem);
        }

        printf("Finish writing\n");

        //--------------------------------------------------------------------------------------

        // Снимаем отображение
        munmap(addr, SHARED_MEMORY_SIZE);

        // Закрываем семафоры
        sem_close(empty_buf_sem);
        sem_close(full_buf_sem);
        sem_close(mutex_sem);

        return 0;
    }
//.........这里部分代码省略.........
开发者ID:AlexSadok,项目名称:Innovations,代码行数:101,代码来源:Programm+producer-consumer.c


示例10: main

int main(int argc, char** argv)
{
  int optchar;
  pthread_t threadid;
  char semaphore_name[32];

  while ((optchar = getopt(argc, argv, "dmp")) != EOF)
  {
    switch (optchar)
    {
    case 'd':
      s_debug = 1;
      break;
    case 'm':
      s_do_mutual_exclusion = 1;
      break;
    case 'p':
      s_do_printf = 1;
      break;
    default:
      assert(0);
    }
  }

  /*
   * Use the ipcs and ipcrm commands to clean up named semaphores left by
   * aborted instances of this process.
   */
  snprintf(semaphore_name, sizeof(semaphore_name), "/drd-sem-open-test-%d",
	   getpid());
  s_sem = sem_open(semaphore_name, O_CREAT | O_EXCL, 0600, 1);
  if (s_sem == SEM_FAILED)
  {
    fprintf(stderr, "Failed to create a semaphore with name %s\n",
            semaphore_name);
    exit(1);
  }

  /*
   * Switch to line-buffered mode, such that timing information can be
   * obtained for each printf() call with strace.
   */
  setlinebuf(stdout);

  if (s_debug)
  {
    printf("&s_d1 = %p; &s_d2 = %p; &s_d3 = %p\n", &s_d1, &s_d2, &s_d3);
  }

  s_d1 = 1;
  s_d3 = 3;

  pthread_create(&threadid, 0, thread_func, 0);

  sleep(1); /* Wait until thread_func() finished. */

  {
    if (s_do_mutual_exclusion) sem_wait(s_sem);
    s_d3++;
    if (s_do_mutual_exclusion) sem_post(s_sem);
  }

  /* Wait until the thread finished. */
  pthread_join(threadid, 0);
  if (s_do_printf) printf("s_d2 = %g (should be 2)\n", s_d2);
  if (s_do_printf) printf("s_d3 = %g (should be 5)\n", s_d3);

  sem_close(s_sem);
  sem_unlink(semaphore_name);

  return 0;
}
开发者ID:AboorvaDevarajan,项目名称:valgrind,代码行数:72,代码来源:sem_open.c


示例11: std_close_proc_sem

extern int std_close_proc_sem(std_proc_sem_id_t semId)
{
    return sem_close((sem_t *) semId) == 0;
}
开发者ID:doinglu,项目名称:cmm,代码行数:4,代码来源:std_port_posix.c


示例12: dinit_filters

void dinit_filters(struct liveStream *ctx)
{
	avfilter_graph_free(&ctx->filter_graph);
	sem_close(&ctx->filter_lock);
}
开发者ID:Open-feather,项目名称:ffmpeg-liveStreaming,代码行数:5,代码来源:filter.c


示例13: main

int main(int argc, char **args) {
    if (argc != 4) {
        printf("Not a suitable number of program parameters\n");
        return (1);
    }
    /************************************
    Utworz semafor posixowy. Ustaw jego wartosc na 1
    *************************************/
    sem_t *sem_id = sem_open(SEM_NAME, O_CREAT, 0600, 1);
    int fd = open(FILE_NAME, O_WRONLY | O_CREAT , 0644);

    int parentLoopCounter = atoi(args[1]);
    int childLoopCounter = atoi(args[2]);

    char buf[50];
    pid_t childPid;
    int max_sleep_time = atoi(args[3]);
    if ((childPid = fork())) {
        int status = 0;
        srand((unsigned) time(0));

        while (parentLoopCounter--) {
            int s = rand() % max_sleep_time + 1;
            sleep(s);
            /**************q****************************
            Sekcja krytyczna. Zabezpiecz dostep semaforem
            ******************************************/
            sem_wait(sem_id);
            sprintf(buf, "Wpis rodzica. Petla %d. Spalem %d\n", parentLoopCounter, s);
            write(fd, buf, strlen(buf));
            write(1, buf, strlen(buf));
            /****************************************************
            Koniec sekcji krytycznej
            ****************************************************/
            sem_post(sem_id);
        }
        waitpid(childPid, &status, 0);
    } else {
        srand((unsigned) time(0));
        while (childLoopCounter--) {
            int s = rand() % max_sleep_time + 1;
            sleep(s);
            /******************************************
            Sekcja krytyczna. Zabezpiecz dostep semaforem
            ******************************************/
            sem_wait(sem_id);
            sprintf(buf, "Wpis dziecka. Petla %d. Spalem %d\n", childLoopCounter, s);
            write(fd, buf, strlen(buf));
            write(1, buf, strlen(buf));
            /****************************************************
            Koniec sekcji krytycznej
            ****************************************************/
            sem_post(sem_id);
        }
        _exit(0);
    }
    /***************************************
    Posprzataj semafor
    ***************************************/
    sem_close(sem_id);
    sem_unlink(SEM_NAME);
    close(fd);
    return 0;
}
开发者ID:Ajris,项目名称:sysopy,代码行数:64,代码来源:main.c


示例14: sem_close

bool CameraStatus::uinitSemaphore(void)
{
	sem_close(this->statusMutex);
	sem_unlink("CCDSTATUS");
	return true;
}
开发者ID:gudbooy,项目名称:OPEL-CameraFramework,代码行数:6,代码来源:cam_status.cpp


示例15: startMiniServer

void startMiniServer(pid_t pidClient){

	Command_e command=DIE;
	DIR *pDir=NULL;
	char strSemNameFifo[MAX_FILE_NAME];
	pthread_t th_fifoController; 

	pDir = opendir(LOCAL_DIR);
	if(pDir==NULL){
		perror("Dir open error :");
		return;
	}

	memset(strSemNameFifo,0,MAX_FILE_NAME);
	sprintf(strSemNameFifo,"/%ld.smf",(long)gPid_server);
	getnamed(strSemNameFifo,&gSemP_fifoSem,1); 
	
	pthread_create(&th_fifoController,NULL,fifoController,NULL);

	pthread_mutex_init(&gMutex_lockSocket,NULL); // initialize mutex

	write(fdClient,&gPid_server,sizeof(pid_t));	//send pid address to client
	while(!doneflag){
		read(fdClient,&command,sizeof(Command_e));
		gettimeofday(&endTime,NULL);
		diffTime = getTimeDif(startTime,endTime);
		if(!doneflag){
			if(command==LS_CLIENT){
				printf("[%ld]MiniServer read LS_CLIENT command from [%ld]Client at %ld ms\n",
				(long)gPid_server,(long)pidClient,diffTime);
				lsClient(fdClient,pidClient);
			}else if(command==LIST_SERVER){
				//lock mutex and write filenames to socket
				printf("[%ld]MiniServer read LIST_SERVER command from [%ld]Client at %ld ms\n",
				(long)gPid_server,(long)pidClient,diffTime);
				pthread_mutex_lock(&gMutex_lockSocket); 
				listLocalFiles(pDir,fdClient);
				pthread_mutex_unlock(&gMutex_lockSocket);
			}else if(command ==DIE){
				printf("[%ld]MiniServer read DIE command from [%ld]Client at %ld ms\n",
				(long)gPid_server,(long)pidClient,diffTime);
				write(fdClient,&command,sizeof(Command_e));
				doneflag=1;
				// TODO: CHANGE DONEFLAG WITH SOMETHING DIFF
			}else if(command == SEND_FILE){
				sendFile(pidClient);
			}
		}
	}

	char fifoName[MAX_FILE_NAME];
	memset(fifoName,0,MAX_FILE_NAME);
	sprintf(fifoName,".%ld.ff",(long)gPid_server);
	int fd = open(fifoName,O_RDWR);
	pid_t killpid=0;
	write(fd,&killpid,sizeof(pid_t));
	close(fd);

	pthread_mutex_destroy(&gMutex_lockSocket);
	pthread_join(th_fifoController,NULL);
	closedir(pDir);
	sem_close(gSemP_fifoSem);
	pDir=NULL; // handle dangling pointers
}
开发者ID:hmenn,项目名称:FTP-Server,代码行数:64,代码来源:serv.c


示例16: onion_poller_free

/// Frees the poller. It first stops it.
void onion_poller_free(onion_poller *p){
	sem_close(p->sem);
	sem_unlink("/poller");
	onion_low_free(p);
}
开发者ID:shinroo,项目名称:TUB_Programs,代码行数:6,代码来源:poller_libev.c


示例17: sendFile

void sendFile(pid_t whosent){

	char fileName[MAX_FILE_NAME];
	long filesize=0;
	pid_t pidArrival=0;
	int i=0;
	char byte;
	int sendServer=0;

	read(fdClient,&pidArrival,sizeof(pid_t));
	memset(fileName,0,MAX_FILE_NAME);
	read(fdClient,fileName,MAX_FILE_NAME);
	read(fdClient,&filesize,sizeof(long));

	gettimeofday(&endTime,NULL);
	diffTime=getTimeDif(startTime,endTime);
	if(pidArrival!=1){ // send client or server
		pid_t pidArrivalServer = getClientServerPid(pidArrival);
		if(pidArrivalServer<=0){
			printf("[%ld]MiniServer want to send file to server in %ld ms\n",
				(long)gPid_server,diffTime);
			sendServer=1;
		}else{ // send client

			printf("[%ld]MiniServer want to send file to [%ld]MiniServer-[%ld]Client pair in %ld ms\n",
						(long)gPid_server,(long)pidArrivalServer,(long)pidArrival,diffTime);

			char fifoName[MAX_FILE_NAME];
			memset(fifoName,0,MAX_FILE_NAME);
			sprintf(fifoName,".%ld.ff",(long)pidArrivalServer);

			char semFifoName[MAX_FILE_NAME];
			memset(semFifoName,0,MAX_FILE_NAME);
			sprintf(semFifoName,".%ld.ffsm",(long)gPid_server);

			int fd = open(fifoName,O_RDWR);
			sem_t *semP;

			getnamed(semFifoName,&semP,1); // fifonun semaforunuda kilitleki
			// sadece tek kişi yazsın içine
			sem_wait(semP);
			write(fd,&whosent,sizeof(pid_t));
			write(fd,fileName,MAX_FILE_NAME);
			int a =write(fd,&filesize,sizeof(long));
			//printf("SizeCheck:%d - %ld\n",a,filesize);
			for(i=0;i!=filesize;++i){
				read(fdClient,&byte,1);
				int a = write(fd,&byte,1); // dosya fifoya yollandi
				//printf("-%c %d\n",byte,a);
			}

			gettimeofday(&endTime,NULL);
			diffTime=getTimeDif(startTime,endTime);
			printf("[%ld]MiniServer sent file: %s (%ld)byte to [%ld]Client in %ld ms\n",
					(long)gPid_server,fileName,filesize,(long)pidArrival,diffTime);
			//close(fd);
			sem_post(semP);
			sem_close(semP);

		}

	}

	if(sendServer==1 || pidArrival==1){
		
		  // SEND SERVER
		// create a sem and lock file in the server
		sem_t *semServerFile;
		char semName[MAX_FILE_NAME+4];
		// prepare semaphore
		memset(semName,0,MAX_FILE_NAME+4);
		sprintf(semName,".%s.sm",fileName);
		getnamed(semName,&semServerFile,1);

		sem_wait(semServerFile);
		gettimeofday(&endTime,NULL);
		diffTime=getTimeDif(startTime,endTime);
		printf("[%ld]MiniServer locked server-file : %s to update in %ld ms\n",
				(long)gPid_server,fileName,diffTime);
		
		unlink(fileName); // delete ol files and create newfile
		int fd = open(fileName,O_RDWR | O_CREAT, S_IRUSR | S_IWUSR| S_IRGRP | S_IROTH);

		gettimeofday(&endTime,NULL);
		diffTime=getTimeDif(startTime,endTime);
		printf("[%ld]MiniServer file: %s transfer started in %ld ms\n",
							(long)gPid_server,fileName,diffTime);
		for(i=0;i!=filesize;++i){
			read(fdClient,&byte,1);
			write(fd,&byte,1);
		}

		gettimeofday(&endTime,NULL);
		diffTime=getTimeDif(startTime,endTime);
		printf("[%ld]MiniServer unlocked(transfer completed) server-file : %s in %ld ms\n",
						(long)gPid_server,fileName,diffTime);
		sem_post(semServerFile);
		sem_close(semServerFile);
		close(fd);

//.........这里部分代码省略.........
开发者ID:hmenn,项目名称:FTP-Server,代码行数:101,代码来源:serv.c


示例18: sem_close

/***
    7. Finalization
***/
void Server::exit()
{
    sem_close(mutex);
}
开发者ID:Garoe,项目名称:ulpgc-dgc-practica2,代码行数:7,代码来源:server.cpp


示例19: main

main(int argc,char *argv[]) { 
	 int i,stat,k, pid, size, fd,res; 
	 bufor_t  *wbuf ; 
	 char c; 
	 // Utworzenie segmentu --------------------------- 
	 shm_unlink("bufor"); 
	 fd=shm_open("bufor", O_RDWR|O_CREAT , 0774); 
	
	 if(fd == -1){ 
		   perror("open"); _exit(-1); 
	 } 
 
 	printf("fd: %d\n",fd); 
 	size = ftruncate(fd,sizeof(bufor_t));   
 	
 	if(size < 0) {perror("trunc"); _exit(-1); } 
 	// Odwzorowanie segmentu fd w obszar pamieci procesow 
 	
 	wbuf = (bufor_t *)mmap(0, sizeof(bufor_t) 
         ,PROT_READ|PROT_WRITE,MAP_SHARED, fd, 0); 
 	
 	if(wbuf == NULL) {perror("map");  _exit(-1); } 
 
 	// Inicjacja obszaru -------------------------------- 
 	wbuf-> cnt = 0; 
 	wbuf->head = 0; 
 	wbuf->tail = 0; 
 
 	if(sem_init(&(wbuf->mutex),1,1)){ 
   		perror("mutex"); _exit(0);  
 	}
 	 
 	if(sem_init(&(wbuf->empty),1,BSIZE)) {  
   		perror("empty"); _exit(0);  
 	}
 	 
 	if(sem_init(&(wbuf->full),1,0)) {  
   		perror("full"); _exit(0);  
 	} 
 
 	// Tworzenie procesow ------------- 
 	if(fork() == 0) { // Producent 
 	   for(i=0;i<10;i++) { 
 	      // printf("Producent: %i\n",i); 
 	      printf("Producent - cnt:%d head: %d tail: %d\n",  
          wbuf-> cnt,wbuf->head,wbuf->tail); 
 	      sem_wait(&(wbuf->empty)); 
       	  sem_wait(&(wbuf->mutex)); 
       	         sprintf(wbuf->buf[wbuf->head],"Komunikat %d",i);  
       wbuf-> cnt ++; 
       wbuf->head = (wbuf->head +1) % BSIZE; 
       sem_post(&(wbuf->mutex)); 
       sem_post(&(wbuf->full)); 
       sleep(1); 
     	}      
     _exit(i); 
 	} 
 	
 	// Konsument ------------------  
 	for(i=0;i<10;i++) { 
    	printf("Konsument - cnt: %d odebrano %s\n",wbuf->cnt  
             ,wbuf->buf[wbuf->tail]);  
     	sem_wait(&(wbuf->full)); 
     	sem_wait(&(wbuf->mutex)); 
     	wbuf-> cnt --; 
     	wbuf->tail = (wbuf->tail +1) % BSIZE; 
     	sem_post(&(wbuf->mutex)); 
     	sem_post(&(wbuf->empty)); 
     	sleep(1); 
 	}
 	      
 	pid = wait(&stat); 
 	sem_close(&(wbuf->mutex)); 
 	sem_close(&(wbuf->empty)); 
 	sem_close(&(wbuf->full)); 
 	
 	return 0; 
} 
开发者ID:krzysztoftc,项目名称:wspolbiezne,代码行数:78,代码来源:semafor.c


示例20: main

int main(int argc, char *argv[])
{
	pid_t pid;
	char *msgbuf;
	size_t buflen;
	int shmid;
	sem_t *semobj;
	char *shmname;
	char *semname;
	char *shmp;

	shmname = path_alloc(NULL);
	if (shmname == NULL)
		err_sys("Cannot allocate memory for path name");

	if (argc == 1)
		strcpy(shmname, "/shmobj");
	else if (argc == 2)
		strncpy(shmname, argv[1], strlen(argv[1]) + 1);
	else
		err_quit("Usage: ./exercise3 (msg_path)");
	if (shmname[0] != '/')
		err_quit("Message queue path name must start with '/'");

	shmid = shm_open(shmname, O_RDWR | O_CREAT, FILE_MODE);
	if (shmid == -1)
		err_sys("Cannot open shared memory");
	if (ftruncate(shmid, MAPSIZ) == -1)
		err_sys("Cannot truncate the file");

	shmp = mmap(NULL, MAPSIZ, PROT_READ | PROT_WRITE, MAP_SHARED,
			shmid, 0);
	if (shmp == NULL)
		err_sys("Cannot map memory to shmobj");

	/* Fetch the allocated size in case for the buffer overrun
	 * with the following strncpy(3)
	 * I don't intend to expose the possiblity for users to define
	 * the path of semaphore as they should not be so interested
	 * in how the program was synchronized :-) */
	semname = path_alloc(&buflen);
	if (semname == NULL)
		err_sys("Cannot allocate memory for semaphore path");
	strncpy(semname, "/tmpsem", buflen);
	semobj = sem_open(semname, O_RDWR | O_CREAT, FILE_MODE, 1);
	if (semobj == SEM_FAILED)
		err_sys("Cannot get the semaphore object!");
	if (sem_init(semobj, !0, 1) == -1)
		err_sys("Cannot initialize semaphore instance");

	if (sem_wait(semobj) == -1)
		err_sys("sem_wait() error");

	pid = fork();
	if (pid < 0) {
		err_sys("Cannot fork new process");
	} else if (!pid) {
		printf("This is the child process, pid: %d\n", getpid());

		/* Well, this sem_open() seems to be redundent since
		 * the entire memory space was copied by fork(). But
		 * problems may be caused due to copy on write when I changed
		 * value of the semaphore. Keeping this sem_open() would have
		 * spared effort dealing with another shmget(2) and copying
		 * semaphore instance into that shared memory */
		semobj = sem_open(semname, O_RDWR);
		if (semobj == SEM_FAILED)
			err_sys("Cannot get the semaphore object!");
		if (sem_wait(semobj) == -1)
			err_sys("sem_wait() error");

		printf("%s\n", shmp);

		if (sem_post(semobj) == -1)
			err_sys("sem_post() error");
		sem_close(semobj);
		exit(0);
	} else {
		printf("This is the parent process, pid: %d\n", getpid());
		msgbuf = (char *) malloc(BUFSIZ);
		sprintf(msgbuf, "This is the message from %d", getpid());
		strcpy(shmp, msgbuf);

		if (sem_post(semobj) == -1)
			err_sys("sem_post() error");

		if (waitpid(pid, NULL, 0) < 0)
			err_sys("Failed to fetch child termination status");
		sem_close(semobj);
	}

	sem_unlink(semname);
	shm_unlink(shmname);
	return 0;
}
开发者ID:hypeboyz,项目名称:OS1_Lab1,代码行数:95,代码来源:exercise4.c



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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