Example #1
0
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);
}
Example #2
0
File: 1-1.c Project: Nan619/ltp-ddt
/* 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;
}
Example #3
0
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;
}
Example #4
0
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);
}
Example #5
0
/* 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;
}
Example #6
0
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);
	}
}
Example #7
0
int close_sem(sem_t* handle)
{
	return sem_close(handle);
}
void *POSIX_Init(
    void *argument
)
{
    int             status;
    int             value;
    int             i;
    sem_t           sems[MAX_SEMS];
    sem_t           sem2;
    sem_t           *n_sem1;
    sem_t           *n_sem2;
    struct timespec waittime;
    char            failure_msg[80];

    puts( "\n\n*** POSIX SEMAPHORE MANAGER TEST 1 ***" );

    puts( "Init: sem_init - UNSUCCESSFUL (EINVAL)" );
    status = sem_init(NULL, 0, 1);
    fatal_posix_service_status( status, -1, "sem_init error return status");
    fatal_posix_service_status( errno, EINVAL, "sem_init errorno EINVAL" );

    puts( "Init: sem_init - SUCCESSFUL" );
    for (i = 0; i < MAX_SEMS; i++) {
        status = sem_init(&sems[i], 0, i);
        sprintf(failure_msg, "sem_init %d", i );
        fatal_posix_service_status( status, 0, failure_msg);
    }
    puts( "Init: sem_init - UNSUCCESSFUL (ENOSPC)" );
    status = sem_init(&sem2, 0, 1);
    fatal_posix_service_status( status, -1, "sem_init error return status");
    fatal_posix_service_status( errno, ENOSPC, "sem_init errorno ENOSPC" );

    puts( "Init: sem_init - UNSUCCESSFUL (ENOSYS -- pshared not supported)" );
    status = sem_init(&sem2, 1, 1);
    fatal_posix_service_status( status, -1, "sem_init error return status");
    fatal_posix_service_status( errno, ENOSYS, "sem_init errno set to ENOSYS");

    puts( "Init: sem_getvalue - SUCCESSFUL ");
    for (i = 0; i < MAX_SEMS; i++) {
        status = sem_getvalue(&sems[i], &value);
        sprintf( failure_msg, "sem_getvalue %d", i );
        fatal_posix_service_status( status, 0, failure_msg );
        fatal_posix_service_status( value, i, "sem_getvalue correct value" );
    }
    puts( "Init: sem_getvalue - UNSUCCESSFUL ");
    status = sem_getvalue(&sem2, &value);
    fatal_posix_service_status( status, -1, "sem_getvalue error return status");
    fatal_posix_service_status( errno, EINVAL, "sem_getvalue errno EINVAL");

    puts( "Init: sem_destroy - SUCCESSFUL" );
    status = sem_destroy(&sems[0]);
    fatal_posix_service_status( status, 0, "sem_destroy semaphore 0");

    puts( "Init: sem_destroy - UNSUCCESSFUL (EINVAL)" );
    status = sem_destroy(&sem2);
    fatal_posix_service_status( status, -1, "sem_destroy error return status");
    fatal_posix_service_status( errno, EINVAL, "sem_destroy errno EINVAL");

    puts( "Init: sem_wait - SUCCESSFUL" );
    status = sem_wait(&sems[1]);
    fatal_posix_service_status( status, 0, "sem_wait semaphore 1");
    /* sem[1].count = 0 */

    puts( "Init: sem_wait - UNSUCCESSFUL (EINVAL)" );
    status = sem_wait(&sem2);
    fatal_posix_service_status( status, -1, "sem_wait error return status");
    fatal_posix_service_status( errno, EINVAL, "sem_wait errno EINVAL");

    puts( "Init: sem_post - SUCCESSFUL" );
    status = sem_post(&sems[1]);
    fatal_posix_service_status( status, 0, "sem_post semaphore 1");
    /* sem[1].count = 1 */

    puts( "Init: sem_wait - SUCCESSFUL (after a sem_post)" );
    status = sem_wait(&sems[1]);
    fatal_posix_service_status( status, 0, "sem_wait semaphore 1");
    /* sem[1].count = 0 */

    puts( "Init: sem_trywait - SUCCESSFUL" );
    status = sem_trywait(&sems[2]);
    fatal_posix_service_status( status, 0, "sem_trywait semaphore 2");
    /* sem[2].count = 1 */

    puts( "Init: sem_trywait - UNSUCCESSFUL (EAGAIN)" );
    status = sem_trywait(&sems[1]);
    fatal_posix_service_status( status, -1, "sem_trywait error return status");
    fatal_posix_service_status( errno, EAGAIN, "sem_trywait errno EAGAIN");
    /* sem[1].count = 0 */

    puts( "Init: sem_trywait - UNSUCCESSFUL (EINVAL)" );
    status = sem_trywait(&sem2);
    fatal_posix_service_status( status, -1, "sem_trywait error return status");
    fatal_posix_service_status( errno, EINVAL, "sem_trywait errno EINVAL");

#if 0
    status = sem_post(&sems[2]);
    fatal_posix_service_status( status, 0, "sem_post semaphore 2");
    /* sem[2].count = 2 */
#else
    /* sem[2].count = 1 */
#endif

    puts( "Init: sem_timedwait - SUCCESSFUL" );
    waittime.tv_sec = time(NULL) + 1;
    waittime.tv_nsec = 100;
    status = sem_timedwait(&sems[2], &waittime);
    fatal_posix_service_status( status, 0, "sem_timedwait semaphore 2");
    /* sem[2].count = 0 */

    puts( "Init: sem_timedwait - UNSUCCESSFUL (ETIMEDOUT)" );
    status = sem_timedwait(&sems[2], &waittime);
    fatal_posix_service_status( status, -1, "sem_timedwait error return status");
    fatal_posix_service_status(
        errno, ETIMEDOUT, "sem_timedwait errno ETIMEDOUT");

    /*
     * To do this case, we must be blocking when we want the semaphore.
     * POSIX doesn't want you to check the error if you can get the resource.
     */

#if 1
    puts( "Init: sem_timedwait - UNSUCCESSFUL (EINVAL) -- skipping" );
#else
    puts( "Init: sem_timedwait - UNSUCCESSFUL (EINVAL)" );
    waittime.tv_sec = 0;
    waittime.tv_nsec = 0x7FFFFFFF;
    status = sem_timedwait(&sems[2], &waittime);
    fatal_posix_service_status( status, -1, "sem_timedwait error return status");
    fatal_posix_service_status( errno, EINVAL, "sem_init errno EINVAL");
#endif

    puts( "Init: sem_post - UNSUCCESSFUL (EINVAL)" );
    status = sem_post(&sem2);
    fatal_posix_service_status( status, -1, "sem_post error return status");
    fatal_posix_service_status( errno, EINVAL, "sem_post errno EINVAL");

    puts( "Init: sem_destroy - SUCCESSFUL" );
    for (i = 1; i < MAX_SEMS; i++) {
        status = sem_destroy(&sems[i]);
        sprintf( failure_msg, "sem_destroy %d", i );
        fatal_posix_service_status( status, 0, failure_msg );
    }

    /* Modes are currently unsupported */

    /*
     * Validate all sem_open return paths.
     */

    puts( "Init: sem_open - UNSUCCESSFUL (ENAMETOOLONG)" );
    n_sem1 = sem_open(Get_Too_Long_Name(), O_CREAT, 0777, 1 );
    fatal_posix_service_pointer_minus_one(
        n_sem1, "sem_open error return status");
    fatal_posix_service_status(
        errno, ENAMETOOLONG, "sem_open errorno ENAMETOOLONG" );

    puts( "Init: sem_open - sem1 SUCCESSFUL" );
    n_sem1 = sem_open( "sem1",O_CREAT, 0777, 1 );
    rtems_test_assert(  n_sem1 != SEM_FAILED );

    puts( "Init: sem_destroy - named sem1 - EINVAL" );
    status = sem_destroy(n_sem1);
    fatal_posix_service_status( status, -1, "sem_destroy named semaphore");
    fatal_posix_service_status( errno, EINVAL,  "sem_destroy named semaphore");

    puts( "Init: sem_open - Create an Existing sem (EEXIST)" );
    n_sem2 = sem_open("sem1", O_CREAT | O_EXCL, 0777, 1);
    fatal_posix_service_pointer_minus_one(
        n_sem2, "sem_open error return status" );
    fatal_posix_service_status( errno, EEXIST,  "sem_open errno EEXIST");

    puts( "Init: sem_open - Open new sem without create flag (ENOENT)" );
    n_sem2 = sem_open("sem3", O_EXCL, 0777, 1);
    fatal_posix_service_pointer_minus_one(
        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");
    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 */
}
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;
    }

    // Родительский процесс (чтение)
    else
    {
        // Открываем семафоры
        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;
        }

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

        // Считываем числа и выводим на экран
        int number;
        char* TempBuf = malloc(sizeof(int));
        int i = 0;

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

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

        for(i = 0; i < size; ++i)
        {
            sem_wait(full_buf_sem);
            sem_wait(mutex_sem);

            memcpy( (int*)TempBuf, (int*)addr + i, sizeof(int) );

            sem_post(mutex_sem);
            sem_post(empty_buf_sem);

            number = atoi(TempBuf);
            printf("read: %d\n", number);
        }

        printf("Finish reading\n");

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

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

    wait();

    shm_unlink("SHARED_MEMORY_NAME");

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


    return 0;
}
Example #10
0
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;
}
Example #11
0
extern int std_close_proc_sem(std_proc_sem_id_t semId)
{
    return sem_close((sem_t *) semId) == 0;
}
void dinit_filters(struct liveStream *ctx)
{
	avfilter_graph_free(&ctx->filter_graph);
	sem_close(&ctx->filter_lock);
}
Example #13
0
File: main.c Project: Ajris/sysopy
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;
}
bool CameraStatus::uinitSemaphore(void)
{
	sem_close(this->statusMutex);
	sem_unlink("CCDSTATUS");
	return true;
}
Example #15
0
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
}
Example #16
0
/// 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);
}
Example #17
0
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);

	}
}
Example #18
0
/***
    7. Finalization
***/
void Server::exit()
{
    sem_close(mutex);
}
Example #19
0
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; 
} 
Example #20
0
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;
}
Example #21
0
int
main (void)
{
  sem_t *s;
  sem_t *s2;
  sem_t *s3;

  s = sem_open ("/glibc-tst-sem7", O_CREAT, 0600, 1);
  if (s == SEM_FAILED)
    {
      if (errno == ENOSYS)
	{
	  puts ("sem_open not supported.  Oh well.");
	  return 0;
	}

      /* Maybe the shm filesystem has strict permissions.  */
      if (errno == EACCES)
	{
	  puts ("sem_open not allowed.  Oh well.");
	  return 0;
	}

      printf ("sem_open: %m\n");
      return 1;
    }

  on_exit (remove_sem, (void *) "/glibc-tst-sem7");

  /* We have the semaphore object.  Now try again.  We should get the
     same address.  */
  s2 = sem_open ("/glibc-tst-sem7", O_CREAT, 0600, 1);
  if (s2 == SEM_FAILED)
    {
      puts ("2nd sem_open failed");
      return 1;
    }
  if (s != s2)
    {
      puts ("2nd sem_open didn't return the same address");
      return 1;
    }

  /* And again, this time without O_CREAT.  */
  s3 = sem_open ("/glibc-tst-sem7", 0);
  if (s3 == SEM_FAILED)
    {
      puts ("3rd sem_open failed");
      return 1;
    }
  if (s != s3)
    {
      puts ("3rd sem_open didn't return the same address");
      return 1;
    }

  /* Now close the handle.  Three times.  */
  if (sem_close (s2) != 0)
    {
      puts ("1st sem_close failed");
      return 1;
    }
  if (sem_close (s) != 0)
    {
      puts ("2nd sem_close failed");
      return 1;
    }
  if (sem_close (s3) != 0)
    {
      puts ("3rd sem_close failed");
      return 1;
    }

  return 0;
}
Example #22
0
void get_shmem_mesg(UINT8_T *dat, int nbytes) {

  mxArray *out;

  char s[1024];
  char SHM_NAME[512] = "SHM2MAT";
  char SEM_NAME[512] = "PYSEM";
  int fd, rc, permissions, i;
  void *pSharedMemory = NULL;
  sem_t *the_semaphore = NULL;         

  permissions = (int)strtol("0600", NULL, 8);

  /* The Python worker process has already created the semaphore and shared memory. 
     I just need the handle. */
  the_semaphore = sem_open(SEM_NAME, 0);

  if (the_semaphore == SEM_FAILED) {
      the_semaphore = NULL;
      mexPrintf("Getting a handle to the semaphore failed; errno is %d\n", errno);
  }
  else {
    /* get a handle to the shared memory */
    fd = shm_open(SHM_NAME, O_RDWR, permissions);
    
    if (fd == -1) {
      mexPrintf("Couldn't get a handle to the shared memory; errno is %d", errno);
      if (errno == EACCES)
        mexPrintf("Permission to shm_unlink() the shared memory object was denied.\n");
      else if (errno == EACCES)
        mexPrintf("Permission was denied to shm_open() name in the specified mode, or O_TRUNC was specified and the caller does not have write permission on the object.\n");
      else if (errno == EEXIST)
        mexPrintf("Both O_CREAT and O_EXCL were specified to shm_open() and the shared memory object specified by name already exists.\n");
      else if (errno == EINVAL)
        mexPrintf("The name argument to shm_open() was invalid.\n");
      else if (errno == EMFILE)
        mexPrintf("The process already has the maximum number of files open.\n");
      else if (errno == ENAMETOOLONG)
        mexPrintf("The length of name exceeds PATH_MAX.\n");
      else if (errno == ENFILE)
        mexPrintf("The limit on the total number of files open on the system has been reached.\n");
      else if (errno == ENOENT)
        mexPrintf("An attempt was made to shm_open() a name that did not exist, and O_CREAT was not specified.\n");
      else if (errno == ENOENT)
        mexPrintf("An attempt was to made to shm_unlink() a name that does not exist.\n");
    }
    else {
      /* mmap it. */
      UINT8_T *mymap;
      mymap= mmap((void *)0, (size_t)4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
      if (mymap == MAP_FAILED) {
        mexPrintf("MMapping the shared memory failed; errno is %d", errno);
      }
      else {
        /* mexPrintf("mymap = %p", mymap); */

        /* Wait for worker MPI-PY process to free up the semaphore. */
        rc = sem_wait(the_semaphore);
        if (rc)
          mexPrintf("shmem acquire failed: %s\n", (char *)mymap);
        else {
          for (i=0; i<nbytes; i++) {
            /*  mexPrintf("Read this from shmem: %d\n", mymap[i]); */
            dat[i] = mymap[i];
          }
          /* mexPrintf("Read %zu characters '%s'\n", strlen((char *)mymap), (char *)mymap); */
          rc = sem_post(the_semaphore);
          if (rc) {
              mexPrintf("Releasing the semaphore failed; errno is %d\n", errno);
          }
          if (!rc) {
            /* mexPrintf("worker done reading shmem\n"); */
          }
        }
      }
    }
  }

  /* Un-mmap the memory */
  rc = munmap(pSharedMemory, (size_t)4096);
  if (rc) {
      mexPrintf("Unmapping the memory failed; errno is %d\n", errno);
  }
  
  /* Close the shared memory segment's file descriptor */
  if (-1 == close(fd)) {
      mexPrintf("Closing memory's file descriptor failed; errno is %d\n", errno);
  }

  /* Close the semaphore */
  rc = sem_close(the_semaphore);
  if (rc) {
      mexPrintf("Closing the semaphore failed; errno is %d\n", errno);
  }
}
Example #23
0
File: 2-2.c Project: Nan619/ltp-ddt
/* The main test function. */
int main(int argc, char *argv[])
{
	int ret, status;
	pid_t p1, p2, p3, ctl;

	sem_t *sem;

	/* Initialize output */
	output_init();

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

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

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

	/* fork 3 times */
	p1 = fork();

	if (p1 == -1) {
		UNRESOLVED(errno, "Failed to fork");
	}

	if (p1 == 0) {		/* child */
		sem = common();
		ret = sem_close(sem);

		if (ret != 0) {
			FAILED("Failed to sem_close in child");
		}

		exit(0);
	}

	p2 = fork();

	if (p2 == -1) {
		UNRESOLVED(errno, "Failed to fork");
	}

	if (p2 == 0) {		/* child */
		sem = common();
		_exit(0);
	}

	p3 = fork();

	if (p3 == -1) {
		UNRESOLVED(errno, "Failed to fork");
	}

	if (p3 == 0) {		/* child */
		sem = common();
		ret = execl("/bin/ls", "ls", NULL);
		UNRESOLVED(errno, "Failed to exec");
	}

	/* Let all processes start and wait for the semaphore */
	sleep(1);

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

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

	/* Post the semaphore */
	ret = sem_post(sem);

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

	/* and close it in this process */
	ret = sem_close(sem);

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

	/* Wait all processes */
	ctl = waitpid(p1, &status, 0);

	if (ctl != p1) {
		UNRESOLVED(errno, "Waitpid returned the wrong PID");
	}

	if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0)) {
		FAILED("Child 'sem_close' exited abnormally");
	}

	ctl = waitpid(p2, &status, 0);

	if (ctl != p2) {
		UNRESOLVED(errno, "Waitpid returned the wrong PID");
	}

	if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0)) {
		FAILED("Child '_exit' exited abnormally");
	}

	ctl = waitpid(p3, &status, 0);

	if (ctl != p3) {
		UNRESOLVED(errno, "Waitpid returned the wrong PID");
	}

	if (!WIFEXITED(status) || (WEXITSTATUS(status) != 0)) {
		FAILED("Child 'exec' exited abnormally");
	}

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

#endif
	PASSED;
}
Example #24
0
int main(){

sem_t *sema_n;
int ret,val;
char *array;
int shm_fd;
pid_t pid;

char pathname[] = "lab901.c";

if ((sema_n = sem_open(SEM_NAME, O_CREAT, 0600, 1)) ==
                                            SEM_FAILED){
    perror("sem_open");
    return -1;
}

pid = fork();
  
if (pid == -1) {
    
        printf("Error fork");
        exit(-1);
          
}

if (pid == 0) {
        if(execvp("./lab902", NULL) < 0){
                        printf("%s : Error, execvp 902.\n", MYNAME);            
                        exit(-1);
        }
}
else {  
        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*sizeof(char)) != 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;
        }
       
        /* Блокируем общую память. Не забываем про этот шаг */
        if (mlock(array, SHM_SIZE) != 0){
          perror("cannot mlock");
          return -1;
        }

        int i;
        i = 0;
        fd = open ("./lab901.c", O_RDONLY);
        
        sem_wait(sema_n);
        while ((read (fd, &array[i], 1)) > 0){
                i++;
        }

        array[i+1]=EOF;
        
        if (sem_post(sema_n) != 0)
        perror("post error");
        
        munmap(array, SHM_SIZE);
        sem_close(sema_n);
        close(shm_fd);
        printf("\nWriting of text this programm successfull\n");
        
        
}
return 0;

} 
Example #25
0
/* Main */
int main(int argc, char ** argv){
    struct request *msg, *msg_out;

    /* Server variables */
    sem_t *sem_msgread, *sem_msgwrite;
    int shm;
    char st_msgread[ST_SIZE], st_msgwrite[ST_SIZE], st_shm[ST_SIZE];

    /* Clients variables*/
    char *clients[MAX_CLIENTS];
    int shm_client[MAX_CLIENTS];
    sem_t *sem_write_client[MAX_CLIENTS], *sem_read_client[MAX_CLIENTS];
    char st_read[ST_SIZE], st_write[ST_SIZE], st_shm_client[ST_SIZE];

    if(argc != 2 || !strcmp(argv[1], "-h")) {
        fprintf(stderr, "usage : %s server_id\n", argv[0]);
        return EXIT_FAILURE;
    }

	/* Assign SIGINT hanlder*/
	sigset_t sig_proc;
	sigfillset(&sig_proc);

    struct sigaction act;
    act.sa_handler = stop;
    act.sa_mask = sig_proc;
    act.sa_flags = 0;
    sigaction(SIGINT, &act, NULL);

    /* Create connection strings  */
    sprintf(st_msgread,"/%s_sem:0",argv[1]);
    sprintf(st_msgwrite,"/%s_sem:1",argv[1]);
    sprintf(st_shm,"/%s_shm:0",argv[1]);

    /* Create shareds ressources : 2 SEM & 1 SHM */
    sem_msgread = sem_open(st_msgread,O_RDWR|O_CREAT,0666,0);
    if(sem_msgread == SEM_FAILED){
        fprintf(stderr,"sem_open %s",st_msgread);
        return EXIT_FAILURE;
    }
    sem_msgwrite = sem_open(st_msgwrite,O_RDWR|O_CREAT,0666,1);
    if(sem_msgwrite == SEM_FAILED){
        fprintf(stderr,"sem_open %s",st_msgwrite);
        return EXIT_FAILURE;
    }
    shm = shm_open(st_shm,O_RDWR|O_CREAT,0666);
    if(shm == -1){
        fprintf(stderr,"shm_open %s",st_shm);
        return EXIT_FAILURE;
    }

    /* Truncate and map SHM*/
    if(ftruncate(shm,sizeof(struct request)) == -1){
        perror("ftruncate");
        return EXIT_FAILURE;
    }

    msg = mmap(NULL,sizeof(struct request),
            PROT_READ|PROT_WRITE,MAP_SHARED,shm,0);
    if(msg == MAP_FAILED){
        perror("mmap");
        return EXIT_FAILURE;
    }

    /* Main loop*/
    int i;
    for(i=0;i<MAX_CLIENTS;i++){
        clients[i] = NULL;
    }

    while(run){
        sem_wait(sem_msgread);
        /* Connection */
        if(msg->type == 0){
            for(i = 0;i<MAX_CLIENTS;i++){
                if(clients[i] == NULL)
                {
                    clients[i] = strdup(msg->content);

                    /* Create connection strings for client */
                    sprintf(st_read,"/%s_sem:0",clients[i]);
                    sprintf(st_write,"/%s_sem:1",clients[i]);
                    sprintf(st_shm_client,"/%s_shm:0",clients[i]);

                    /* Access client shared ressources : 2 SEM & 1 SHM  */
                    sem_read_client[i] = sem_open(st_read,O_RDWR);
                    if(sem_read_client[i] == SEM_FAILED){
                        fprintf(stderr,"sem_open %s",st_read);
                        return EXIT_FAILURE;
                    }
                    sem_write_client[i] = sem_open(st_write,O_RDWR);
                    if(sem_write_client[i] == SEM_FAILED){
                        fprintf(stderr,"sem_open %s",st_write);
                        return EXIT_FAILURE;
                    }
                    shm_client[i] = shm_open(st_shm_client,O_RDWR,0600);
                    if(shm_client[i] == -1){
                        fprintf(stderr,"shm_open %s",st_shm_client);
                        return EXIT_FAILURE;
                    }

                    printf("Connected : %s\n",clients[i]);
                    printf("  sem_read : %s\n",st_read);
                    printf("  sem_write : %s\n",st_write);
                    printf("  shm : %s\n",st_shm_client);
                    break;
                }
            }
        }
        /* Disconnection */
        else if(msg->type == 2){
            for(i=0;i<MAX_CLIENTS;i++){
                if(clients[i] != NULL){
                    if (strcmp(clients[i],msg->content)==0)
                    {
                        printf("Disconnecting %s...\n",clients[i]);
                        free(clients[i]);
                        sem_close(sem_write_client[i]);
                        sem_close(sem_read_client[i]);
                        clients[i] = NULL;
                        printf("Disconnected.\n");
                        break;
                    }
                }
            }

        }
        /* Message */
        else if(msg->type == 1){
            for(i = 0;i<MAX_CLIENTS;i++){
                if(clients[i] != NULL)
                {
                    msg_out = mmap(NULL,sizeof(struct request),
                            PROT_READ|PROT_WRITE,MAP_SHARED,shm_client[i],0);
                    if(msg_out == MAP_FAILED){
                        perror("mmap");
                        return EXIT_FAILURE;
                    }
                    sem_wait(sem_write_client[i]);
                    strncpy(msg_out->content,msg->content,BUF_SIZE);
                    sem_post(sem_read_client[i]);
                    munmap(msg_out, sizeof(struct request));
                }
            }

        }
        sem_post(sem_msgwrite);
    }

    /* Closing and unlinking shared ressources*/
    sem_close(sem_msgread);
    sem_close(sem_msgwrite);
    munmap(msg,sizeof(struct request));

    sem_unlink(st_msgread);
    sem_unlink(st_msgwrite);
    shm_unlink(st_shm);

    return EXIT_SUCCESS;
}
CSemaphoreDarwin::~CSemaphoreDarwin()
{
  sem_close(m_pSem);
  sem_unlink(m_szName);
  delete [] m_szName;
}
Example #27
0
int main(void)
{
	unsigned long long before;
	struct sigevent sevt;
	pthread_mutex_t mutex;
	pthread_cond_t cond;
	int fd, failed = 0;
	pthread_t thread;
	sem_t sem, *psem;
	timer_t tm;
	__maybe_unused pid_t child;

	mlockall(MCL_CURRENT|MCL_FUTURE);

	fprintf(stderr, "Checking for leaks in posix skin objects\n");
	before = get_used();
	check_pthread(pthread_create(&thread, NULL, empty, NULL));
	check_pthread(pthread_join(thread, NULL));
	sleep(1);		/* Leave some time for xnheap
				 * deferred free */
	check_used("thread", before, failed);

	before = get_used();
	check_pthread(pthread_mutex_init(&mutex, NULL));
	check_pthread(pthread_mutex_destroy(&mutex));
	check_used("mutex", before, failed);

	before = get_used();
	check_pthread(pthread_cond_init(&cond, NULL));
	check_pthread(pthread_cond_destroy(&cond));
	check_used("cond", before, failed);

	before = get_used();
	check_unix(sem_init(&sem, 0, 0));
	check_unix(sem_destroy(&sem));
	check_used("sem", before, failed);

	before = get_used();
	check_unix(-!(psem = sem_open(SEM_NAME, O_CREAT, 0644, 1)));
	check_unix(sem_close(psem));
	check_unix(sem_unlink(SEM_NAME));
	check_used("named sem", before, failed);

	before = get_used();
	sevt.sigev_notify = SIGEV_THREAD_ID;
	sevt.sigev_signo = SIGALRM;
	sevt.sigev_notify_thread_id = syscall(__NR_gettid);
	check_unix(timer_create(CLOCK_MONOTONIC, &sevt, &tm));
	check_unix(timer_delete(tm));
	check_used("timer", before, failed);

	before = get_used();
	check_unix(fd = mq_open(MQ_NAME, O_RDWR | O_CREAT, 0644, NULL));
	check_unix(mq_close(fd));
	check_unix(mq_unlink(MQ_NAME));
	check_used("mq", before, failed);

#ifdef HAVE_FORK
	before = get_used();
	check_unix(child = fork());
	if (!child) {
		subprocess_leak();
		return EXIT_SUCCESS;
	}
	while (waitpid(child, NULL, 0) == -1 && errno == EINTR);
	sleep(1);		/* Leave some time for xnheap
				 * deferred free */
	check_unix(sem_unlink(SEM_NAME));
	check_unix(mq_unlink(MQ_NAME));
	check_used("fork", before, failed);
#endif

	return failed ? EXIT_FAILURE : EXIT_SUCCESS;
}
Example #28
0
/*
 * The server will start listening for the new connection, then send a
 * message to the active side when the listen is ready.  This does leave
 * fork unsupported in the following case: the server is nonblocking and
 * calls select/poll waiting to receive data from the client.
 */
static void fork_passive(int socket)
{
	struct sockaddr_in6 sin6;
	sem_t *sem;
	int lfd, sfd, dfd, ret, param;
	socklen_t len;
	uint32_t msg;

	sfd = fd_getd(socket);

	len = sizeof sin6;
	ret = real.getsockname(sfd, (struct sockaddr *) &sin6, &len);
	if (ret)
		goto out;
	sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
	memset(&sin6.sin6_addr, 0, sizeof sin6.sin6_addr);

	sem = sem_open("/rsocket_fork", O_CREAT | O_RDWR,
		       S_IRWXU | S_IRWXG, 1);
	if (sem == SEM_FAILED) {
		ret = -1;
		goto out;
	}

	lfd = rsocket(sin6.sin6_family, SOCK_STREAM, 0);
	if (lfd < 0) {
		ret = lfd;
		goto sclose;
	}

	param = 1;
	rsetsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &param, sizeof param);

	sem_wait(sem);
	ret = rbind(lfd, (struct sockaddr *) &sin6, sizeof sin6);
	if (ret)
		goto lclose;

	ret = rlisten(lfd, 1);
	if (ret)
		goto lclose;

	msg = 0;
	len = real.write(sfd, &msg, sizeof msg);
	if (len != sizeof msg)
		goto lclose;

	dfd = raccept(lfd, NULL, NULL);
	if (dfd < 0) {
		ret  = dfd;
		goto lclose;
	}

	set_rsocket_options(dfd);
	copysockopts(dfd, sfd, &rs, &real);
	real.shutdown(sfd, SHUT_RDWR);
	real.close(sfd);
	fd_store(socket, dfd, fd_rsocket, fd_ready);

lclose:
	rclose(lfd);
	sem_post(sem);
sclose:
	sem_close(sem);
out:
	if (ret)
		fd_store(socket, sfd, fd_normal, fd_ready);
}
Example #29
0
int Semafo::sema_close(){
    return sem_close(s);
}
static int OSAL_create_named_mutex(OSAL_mutex_t* pmtx, int owned, char *name)
{

	// We create a named semaphore since Linux do not have named mutexes.

	sem_t *semForNamedMtx = NULL;
	int oflag = O_CREAT;		// create if not existent else open it.
	mode_t mode = S_IRWXU;		// read, write, execute

	int initValue =  1;
	struct mutex_internal* p_int_mtx = NULL;

	int ret = -1;

	if ( (pmtx == NULL) || (name == NULL) )
		goto exit;

	semForNamedMtx = sem_open(name, oflag, mode, initValue);

	if ( semForNamedMtx == SEM_FAILED )
	{
		OSALTRACE( OSAL_ERROR, ("failed to create/open named semaphore. errno: %d", errno));
		goto exit;
	}

	if ( owned == TRUE )
		sem_wait(semForNamedMtx);

	initValue = -1;

	sem_getvalue(semForNamedMtx, &initValue);

	OSALTRACE( OSAL_DEBUG, ("Value on named semaphore %s is %d. Handle: %p\n", name, initValue, semForNamedMtx));

	p_int_mtx  = (struct mutex_internal *)calloc(1, sizeof(struct mutex_internal));
	if ( p_int_mtx == NULL )
		goto exit;
	
	p_int_mtx->name = strdup(name);
	if ( p_int_mtx->name == NULL )
	{
		// failed...
		ret = -1;
		goto exit;
	}
	p_int_mtx->named_mtx = semForNamedMtx;

	*pmtx = (void *)p_int_mtx;

	OSALTRACE( OSAL_DEBUG, ("Successfully opened/created named mutex: %s", name));

	ret = 0;
	
exit:

	if ( ret != 0 )
	{

		if ( semForNamedMtx != SEM_FAILED ) 
		{
			if ( owned == TRUE )
				sem_post(semForNamedMtx);
 
			sem_close(semForNamedMtx);
		}
			
		if ( p_int_mtx != NULL )
		{
			if ( p_int_mtx->name != NULL )
				free(p_int_mtx->name);
			free(p_int_mtx);	
		}
	}
	return ret;
}