Пример #1
0
int main(int argc, char *argv[])
{
	int ret, id,  use_clone = T_NONE;
	char *tsttype = NONESTR;
	char buf[7];

	if (argc != 2) {
		tst_resm(TINFO, "Usage: %s <clone| unshare| none>", argv[0]);
		tst_resm(TINFO, " where clone, unshare, or fork specifies"
				" unshare method.\n");
		tst_exit();
	}

	/* Using PIPE's to sync between container and Parent */
	if (pipe(p1) == -1) { perror("pipe1"); tst_exit(); }
	if (pipe(p2) == -1) { perror("pipe2"); tst_exit(); }

	if (strcmp(argv[1], "clone") == 0) {
		use_clone = T_CLONE;
		tsttype = CLONESTR;
	} else if (strcmp(argv[1], "unshare") == 0) {
		use_clone = T_UNSHARE;
		tsttype = UNSHARESTR;
	}

	tst_resm(TINFO, "Semaphore Namespaces Test : %s", tsttype);

	/* Create 2 containers */
	ret = do_clone_unshare_test(use_clone, CLONE_NEWIPC, check_sem1, NULL);
	if (ret < 0) {
		tst_resm(TFAIL, "clone/unshare failed\n");
		tst_exit();
	}

	ret = do_clone_unshare_test(use_clone, CLONE_NEWIPC, check_sem2, NULL);
	if (ret < 0) {
		tst_resm(TFAIL, "clone/unshare failed\n");
		tst_exit();
	}
	close(p2[1]);
	read(p2[0], buf, 7);

	if (strcmp(buf, "exists") == 0)
		if (use_clone == T_NONE)
			tst_resm(TPASS, "Plain cloned process able to access the semaphore "
							"created\n");
		else
			tst_resm(TFAIL, "%s : In namespace2 found the semaphore "
							"created in Namespace1\n", tsttype);
	else
		if (use_clone == T_NONE)
			tst_resm(TFAIL, "Plain cloned process didn't find semaphore\n");
		else
			tst_resm(TPASS, "%s : In namespace2 unable to access the semaphore "
							"created in Namespace1\n", tsttype);

	/* Delete the semaphore */
	id = semget(MY_KEY, 1, 0);
	semctl(id, IPC_RMID, 0);
	tst_exit();

	return 0;
}
Пример #2
0
int mysem_init(mysem_t *sem, int pshared, unsigned int value){
	if ((*sem = semget(IPC_PRIVATE, 1, PERMS)) == -1)
		return -1;
	return 0;
}
Пример #3
0
/******************************************************************************
 *                                                                            *
 * Function: zbx_mutex_create_ext                                             *
 *                                                                            *
 * Purpose: Create the mutex                                                  *
 *                                                                            *
 * Parameters:  mutex - handle of mutex                                       *
 *              name - name of mutex (index for nix system)                   *
 *              forced - remove mutex if exists (only for nix)                *
 *                                                                            *
 * Return value: If the function succeeds, then return ZBX_MUTEX_OK,          *
 *               ZBX_MUTEX_ERROR on an error                                  *
 *                                                                            *
 * Author: Eugene Grigorjev                                                   *
 *                                                                            *
 * Comments: use alias 'zbx_mutex_create' and 'zbx_mutex_create_force'        *
 *                                                                            *
 ******************************************************************************/
int zbx_mutex_create_ext(ZBX_MUTEX *mutex, ZBX_MUTEX_NAME name, unsigned char forced)
{
#ifdef _WINDOWS

	if (NULL == (*mutex = CreateMutex(NULL, FALSE, name)))
	{
		zbx_error("error on mutex creating: %s", strerror_from_system(GetLastError()));
		return ZBX_MUTEX_ERROR;
	}

#else

#define ZBX_MAX_ATTEMPTS	10
	int		attempts = 0, i;
	key_t		sem_key;
	union semun	semopts;
	struct semid_ds	seminfo;

	if (-1 == (sem_key = ftok(CONFIG_FILE, (int)'z')))
	{
		zbx_error("cannot create IPC key for path '%s', try to create for path '.': %s",
				CONFIG_FILE, zbx_strerror(errno));

		if (-1 == (sem_key = ftok(".", (int)'z')))
		{
			zbx_error("cannot create IPC key for path '.': %s", zbx_strerror(errno));
			return ZBX_MUTEX_ERROR;
		}
	}
lbl_create:
	if (-1 != ZBX_SEM_LIST_ID || -1 != (ZBX_SEM_LIST_ID = semget(sem_key, ZBX_MUTEX_COUNT, IPC_CREAT | IPC_EXCL | 0600 /* 0022 */)) )
	{
		/* set default semaphore value */

		semopts.val = 1;
		for (i = 0; ZBX_MUTEX_COUNT > i; i++)
		{
			if (-1 == semctl(ZBX_SEM_LIST_ID, i, SETVAL, semopts))
			{
				zbx_error("semaphore [%i] error in semctl(SETVAL): %s", name, zbx_strerror(errno));
				return ZBX_MUTEX_ERROR;

			}

			zbx_mutex_lock(&i);	/* call semop to update sem_otime */
			zbx_mutex_unlock(&i);	/* release semaphore */
		}
	}
	else if (EEXIST == errno)
	{
		ZBX_SEM_LIST_ID = semget(sem_key, 0 /* get reference */, 0600 /* 0022 */);

		if (1 == forced)
		{
			if (0 != semctl(ZBX_SEM_LIST_ID, 0, IPC_RMID, 0))
			{
				zbx_error("cannot recreate Zabbix semaphores for IPC key 0x%lx Semaphore ID %ld: %s",
						sem_key, ZBX_SEM_LIST_ID, zbx_strerror(errno));
				exit(EXIT_FAILURE);
			}

			/* semaphore is successfully removed */
			ZBX_SEM_LIST_ID = -1;

			if (ZBX_MAX_ATTEMPTS < ++attempts)
			{
				zbx_error("cannot recreate Zabbix semaphores for IPC key 0x%lx: too many attempts",
						sem_key);
				exit(EXIT_FAILURE);
			}

			if ((ZBX_MAX_ATTEMPTS / 2) < attempts)
				zbx_sleep(1);

			goto lbl_create;
		}

		semopts.buf = &seminfo;
		/* wait for initialization */
		for (i = 0; ZBX_MUTEX_MAX_TRIES > i; i++)
		{
			if (-1 == semctl(ZBX_SEM_LIST_ID, 0, IPC_STAT, semopts))
			{
				zbx_error("semaphore [%i] error in semctl(IPC_STAT): %s",
						name, zbx_strerror(errno));
				break;
			}

			if (0 != semopts.buf->sem_otime)
				goto lbl_return;

			zbx_sleep(1);
		}

		zbx_error("semaphore [%i] not initialized", name);
		return ZBX_MUTEX_ERROR;
	}
	else
	{
		zbx_error("cannot create Semaphore: %s", zbx_strerror(errno));
		return ZBX_MUTEX_ERROR;
	}
lbl_return:
	*mutex = name;
	mutexes++;

#endif	/* _WINDOWS */

	return ZBX_MUTEX_OK;
}
Пример #4
0
int main()
{
int i;
int prio_inheritance=0;

/************************************ Process 2 (Low Priority) **********************************/
		
	int PID_L = getpid();
	int PR_L = getpriority(PRIO_PROCESS,PID_L);
	printf("The Priority of LOW Process %d = %d\n", PID_L,PR_L);

	key_t key;
        int shm_id;
        char *shm, *s;
        char c;

        key = 5788; // name the shared memory
        shm_id= shmget(key,100, IPC_EXCL | 0666); // make a shared memory of 27 bytes
        if(shm_id < 0)
        {
                perror("shmget");
                exit(1);
        }
        // Now attach the shared memory to our data space
        if((shm = shmat(shm_id,NULL,0)) == (char *) -1)
        {
                perror("shmat");
                exit(1);
        }

		sem_id = semget(key,1,0666 | IPC_CREAT);
                if(!set_semvalue())
                {
                        fprintf(stderr,"Failed to initiaalize the semaphore \n");
                        exit(EXIT_FAILURE);
                }


       /*
	  FILE *f = fopen("shared_mem_info.txt","r");
        if (f == NULL)
        {
                printf("Error in opening file!!! \n");
                exit(1);
        }
        fscanf(f,"%d",&shm_id);
        fclose(f);
        printf("shared memory id = %d \n",shm_id);
	*/
printf("Address = %d\n",shm);
	for(s=shm; *s !=NULL; s++)
	{
		putchar(*s);
	}
	putchar('\n');

	union semun sem_union;
        who_locked = semctl(sem_id,0,GETPID,sem_union);
       
               if(who_locked > 0)
                {
                        printf("The PID = %d has locked the Semaphore. . . \n",who_locked);
                       /* setpriority(PRIO_PROCESS,who_locked,PRIO_H);
                        prio_inheritance = 1;
                        printf("The PID = %d has inherited priority of High that is %d...\n",who_locked,PRIO_H);
                        sched_yield();*/
                }
    

	sem_lock();
        printf("High process has acquired the lock\n");


	*shm='*';

	/*Low Priority Task tries to acquire to lock the semaphore*/
/*		sem_lock();
		printf("Low Priority Process locks semaphore\n");
		for(i=0;i<50;i++)
		printf("Low Prio task is running...\n");
		sem_unlock();
		printf("Low Priority task is completed...\n");
		printf("Inheritance = %d \n",prio_inheritance);
		prio_inheritance = 0;
		printf("Inheritance = %d \n",prio_inheritance);
*/					 	
	return 0;

}
Пример #5
0
//---------------------------------------------------------------
// svipc_sem_init
//---------------------------------------------------------------
int svipc_sem_init(key_t key, int numslots)
{
  int i, status;
  int sempoolid = -1;

  Debug(5, "svipc_sem_init %x\n", key);

  if (numslots > 0)
    {
      sempoolid =
        semget(key, numslots,
               IPC_CREAT | IPC_PRIVATE | IPC_EXCL | 0666);

      if (sempoolid == -1)
        {
          perror("sempoolid semget failed");
          return -1;
        }

      // all semaphores are locked at startup
      union semun semctlops;
      semctlops.val = 0;

      // fixme - SETALL perf improvement
      for (i = 0; i < numslots; i++)
        {
          status = semctl(sempoolid, i, SETVAL, semctlops);

          if (status == -1)
            {
              perror("sempoolid semctl failed");
              return -1;
            }
        }
    }

  else if (numslots == 0)
    {
      // reset all the semaphores at 0 (hack functionality)
      sempoolid = semget(key, 0, 0666);

      if (sempoolid == -1)
        {
          perror("sempoolid semget failed");
          return -1;
        }

      // find out how many sem are in the pool
      union semun semctlops;
      struct semid_ds stat;
      unsigned int i;
      semctlops.buf = &stat;
      status = semctl(sempoolid, 0, IPC_STAT, semctlops);

      if (status == -1)
        {
          perror("semctl IPC_STAT failed");
          return -1;
        }

      for (i = 0; i < stat.sem_nsems; i++)
        {
          semctlops.val = 0;
          status = 0;
          status |= semctl(sempoolid, i, SETVAL, semctlops);
        }

      if (status == -1)
        {
          perror("sempoolid semctl failed");
          return -1;
        }
    }

  else
    {
      // noop, print info
      return svipc_sem_info(key, 1);
    }

  return 0;
}
Пример #6
0
int
run_processes(const struct proc_spec *specs, uint16_t count)
{
	const int SEMFLAG = IPC_CREAT | IPC_EXCL | 0600;

	union semun	sem_arg;
	struct sembuf	sem_op;
	unsigned short	sem_init[] = { 0, 0 };
	pid_t		*children = 0;
	unsigned	seed;
	int		semid = -1;
	int		status;

	if (!(children = calloc(count, sizeof(pid_t)))) {
		fprintf(stderr, "%s: out of memory\n", prog);
		status = -1;
		goto end;
	}

	/* create semaphore, serves as a barrier */
	if ((semid = semget(IPC_PRIVATE, 1, SEMFLAG)) == -1) {
		fprintf(stderr, "%s: semget failed: %s\n",
		    prog, strerror(errno));
		status = -1;
		goto end;
	}

	/* initialize semaphore values to 0 */
	sem_arg.array = sem_init;
	if (semctl(semid, 0, SETALL, sem_arg) == -1) {
		fprintf(stderr, "%s: semctl(SETVAL) failed: %s\n",
		    prog, strerror(errno));
		status = -1;
		goto end;
	}

	/* all processes need to be seeded seperately, so this gets
	 * incremented in the loop */
	seed = time(0);

	/* start workers */
	for (uint16_t i = 0; i < count; i++) {
		pid_t pid = fork();
		if (pid == -1) {
			fprintf(stderr, "%s: fork failed: %s\n",
			    prog, strerror(errno));
			status = -1;
			goto end;
		} else if (!pid) {
			srand(seed);
			if (worker_begin(specs + i, semid) == -1)
				exit(1);
			exit(0);
		}
		children[i] = pid;
		seed++;
	}

	/* spin until all processes are waiting on the semaphore, or one
	 * process ends prematurely */
	for (;;) {
		pid_t pid;
		int val;

		if ((val = semctl(semid, 0, GETNCNT)) == -1) {
			fprintf(stderr, "%s: semctl(GETNCNT) failed: %s\n",
			    prog, strerror(errno));
			status = -1;
			goto end;
		}
		if (val == count) break; /* ready */

		if ((pid = waitpid(-1, 0, WNOHANG)) == -1) {
			fprintf(stderr, "%s: waitpid failed: %s\n",
			    prog, strerror(errno));
			status = -1;
			goto end;
		} else if (pid) {
			fprintf(stderr, "%s: at least one process exited "
			    "prematurely\n", prog);
			status = -1;
			goto end;
		}

		sched_yield();
	}

	/* release the processes to start*/
	sem_op.sem_num = 0;
	sem_op.sem_op = count;
	sem_op.sem_flg = 0;
	if (semop(semid, &sem_op, 1) == -1) {
		fprintf(stderr, "%s: failed to signal semaphore: %s\n",
		    prog, strerror(errno));
		status = -1;
		goto end;
	}

	/* spin until all processes are waiting on the semaphore, or one
	 * process ends prematurely */
	for (;;) {
		pid_t pid;
		int val;

		if ((val = semctl(semid, 0, GETNCNT)) == -1) {
			fprintf(stderr, "%s: semctl(GETNCNT) failed: %s\n",
			    prog, strerror(errno));
			status = -1;
			goto end;
		}
		if (val == count) break; /* all done working */

		if ((pid = waitpid(-1, 0, WNOHANG)) == -1) {
			fprintf(stderr, "%s: waitpid failed: %s\n",
			    prog, strerror(errno));
			status = -1;
			goto end;
		} else if (pid) {
			fprintf(stderr, "%s: at least one process exited "
			    "prematurely\n", prog);
			status = -1;
			goto end;
		}

		sched_yield();
	}

	/* release the processes to clean up */
	sem_op.sem_num = 0;
	sem_op.sem_op = count;
	sem_op.sem_flg = 0;
	if (semop(semid, &sem_op, 1) == -1) {
		fprintf(stderr, "%s: failed to signal semaphore: %s\n",
		    prog, strerror(errno));
		status = -1;
		goto end;
	}

	/* wait for children to exit */
	for (uint16_t running = count; running;) {
		int		child_status = 0;
		pid_t		pid;
		uint16_t	id;

		if ((pid = waitpid(-1, &child_status, 0)) == -1) {
			assert(errno == EINTR);
			continue;
		}

		for (id = 0; id < count; id++)
			if (children[id] == pid) break;
		assert(id != count);

		children[id] = 0;
		running--;

		if (WIFEXITED(child_status)) {
			if (WEXITSTATUS(child_status)) {
				fprintf(stderr,
				    "%s: process %hu exited with %d\n",
				    prog, id, WEXITSTATUS(child_status));
				status = -1;
				goto end;
			}
		} else {
			int signum = WTERMSIG(child_status);
			fprintf(stderr,
			    "%s: process %hu terminated with %s (%d)\n",
			    prog, id, signame(signum), signum);
			status = -1;
			goto end;
		}
	}

	status = 0;
end:
	if (children) {
		for (uint16_t i = 0; i < count; i++)
			if (children[i])
				/* this line reads quite well */
				kill(children[i], SIGKILL);
		/* if the children have all been killed, I don't know what
		 * good it does to free them */
		free(children);
	}
	if (semid != -1) {
		if (semctl(semid, 0, IPC_RMID) == -1) {
			fprintf(stderr,
			    "%s: semctl(IPC_RMID) failed: %s\n",
			    prog, strerror(errno));
			status = -1;
		}
	}
	return status;
}
Пример #7
0
key_t QSystemSemaphorePrivate::handle(QSystemSemaphore::AccessMode mode)
{
    if (-1 != unix_key)
        return unix_key;

    if (key.isEmpty()) {
        errorString = QCoreApplication::tr("%1: key is empty", "QSystemSemaphore").arg(QLatin1String("QSystemSemaphore::handle"));
        error = QSystemSemaphore::KeyError;
        return -1;
    }

    // ftok requires that an actual file exists somewhere
    int built = QSharedMemoryPrivate::createUnixKeyFile(fileName);
    if (-1 == built) {
        errorString = QCoreApplication::tr("%1: unable to make key", "QSystemSemaphore").arg(QLatin1String("QSystemSemaphore::handle"));
        error = QSystemSemaphore::KeyError;
        return -1;
    }
    createdFile = (1 == built);

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

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

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

    return unix_key;
}
Пример #8
0
int main( int argc, char *argv[] )
{

  //create a key
  key_t key;
  key = ftok( FILE_FOR_KEY, 0 );
  if( key == -1 )
  {
    printf( "%s: can't create a key\n", argv[0] );
    exit(-1);
  }

  // create shared memory
  int shm_id;
  shm_id = shmget( key , SHM_SIZE, IPC_CREAT | IPC_EXCL | 0777 );

  if( shm_id == -1 )
  {
    if( errno != EEXIST )
    {
      printf( "%s: can't create shared memory\n", argv[0] );
      exit(-1);
    }
    else
    {
      shm_id = shmget( key , SHM_SIZE, 0 );
      if( shm_id == -1 )
      {
        printf( "%s; can't open shared memory\n", argv[0] );
        exit(-1);
      }
    }
  }

  //attach shared memory
  struct msg * shm_adr;
  shm_adr = (struct msg *) shmat( shm_id, NULL, 0 );
  if( shm_adr == (void *) -1 )
  {
    printf( "%s; can't attach  shared memory\n", argv[0] );
    exit(-1);
  }
  
  //create semaphores
  int sem_id;
  sem_id = semget( key , 4, IPC_CREAT | IPC_EXCL | 0777 );

  if( sem_id == -1 )
  {
    if( errno != EEXIST )
    {
      printf( "%s: can't create semaphores\n", argv[0] );
      exit(-1);
    }
    else
    {
      sem_id = semget( key , 4, 0 );
      if( sem_id == -1 )
      {
        printf( "%s; can't open semaphores\n", argv[0] );
        exit(-1);
      }
    }
  }

  //--------------------------------------------------------------
  if( argc == 2 )
  {
    //sender
    
    //open file
    int fd;
    fd = open( argv[1], O_RDONLY );
    if( fd == -1 )
    {
      printf( "%s: can't open %s\n", argv[0], argv[1] );
      exit(-1);
    }
    
    //copy from file fo shared memory
    int read_amount, ret_val;
   
    //if sender is already exist
    //snd 0
    sem_ops[0].sem_num = 0;
    sem_ops[0].sem_op = 0;
    sem_ops[0].sem_flg = IPC_NOWAIT;
    //snd +1
    sem_ops[1].sem_num = 0;
    sem_ops[1].sem_op = 1;
    sem_ops[1].sem_flg = SEM_UNDO;
    //operations
    ret_val = semop( sem_id, &sem_ops[0], 2 );
    if( ( ret_val != 0 ) && ( errno == EAGAIN ) )
    {
      printf("%s: sender is already exist\n", argv[0] );
      exit(-1);
    }
    //cr section 1 ->
    
    //wait for reciever
    //rcv -1
    sem_ops[0].sem_num = 1;
    sem_ops[0].sem_op = -1;
    sem_ops[0].sem_flg = 0;
    //rcv +1
    sem_ops[1].sem_num = 1;
    sem_ops[1].sem_op = 1;
    sem_ops[1].sem_flg = 0;
    //operations
    ret_val = semop( sem_id, &sem_ops[0], 2 );
 
    do
    {
      //rcv -1
      sem_ops[0].sem_num = 1;
      sem_ops[0].sem_op = -1;
      sem_ops[0].sem_flg = IPC_NOWAIT;
      //rcv +1
      sem_ops[1].sem_num = 1;
      sem_ops[1].sem_op = 1;
      sem_ops[1].sem_flg = SEM_UNDO;
      //empty -1
      sem_ops[2].sem_num = 2;
      sem_ops[2].sem_op = -1;
      sem_ops[2].sem_flg = 0;
      //operations
      ret_val = semop( sem_id, &sem_ops[0], 3);
      if( ( ret_val != 0) && ( errno == EAGAIN ) )
      {
        printf("%s: reciever crashed\n", argv[0] );
        exit(-1);
      }
      //cr section 2 ->
      read_amount = read( fd, shm_adr -> buf, BUF_SIZE );
      shm_adr -> amount = read_amount;
      // <- 2

      // <- 1

      //full +1
      sem_ops[0].sem_num = 3;
      sem_ops[0].sem_op = 1;
      sem_ops[0].sem_flg = SEM_UNDO;
      //operations
      ret_val = semop( sem_id, &sem_ops[0], 1);

    } while ( read_amount == BUF_SIZE );
    
    //ending
    close( fd );
    shmdt( shm_adr );
    //printf( "%s: end\n", argv[0] );
    exit(0);
  }
  //------------------------------------------------------------
  if( argc == 1 )
  {
    //reciever

    //copy from shared memory to stdout
    int write_amount, ret_val;
    //if reciever is already exist
    //rcv 0
    sem_ops[0].sem_num = 1;
    sem_ops[0].sem_op = 0;
    sem_ops[0].sem_flg = IPC_NOWAIT;
    //rcv +1
    sem_ops[1].sem_num = 1;
    sem_ops[1].sem_op = 1;
    sem_ops[1].sem_flg = SEM_UNDO;
    //operations
    ret_val = semop( sem_id, &sem_ops[0], 2);
    if( ( ret_val != 0) && ( errno == EAGAIN ) )
    {
      printf("%s: reciever is already exist\n", argv[0] );
      exit(-1);
    }
    //cr section 1 ->

    //wait for sender
    //snd -1
    sem_ops[0].sem_num = 0;
    sem_ops[0].sem_op = -1;
    sem_ops[0].sem_flg = 0;
    //snd +1
    sem_ops[1].sem_num = 0;
    sem_ops[1].sem_op = 1;
    sem_ops[1].sem_flg = 0;
    //operations
    ret_val = semop( sem_id, &sem_ops[0], 2);

    //inintialize empty = 1
    sem_ops[0].sem_num = 2;
    sem_ops[0].sem_op = 1;
    sem_ops[0].sem_flg = SEM_UNDO;
    //operations
    ret_val = semop( sem_id, &sem_ops[0], 1);
    
    do
    {
      //snd -1
      sem_ops[0].sem_num = 0;
      sem_ops[0].sem_op = -1;
      sem_ops[0].sem_flg = IPC_NOWAIT;
      //snd +1
      sem_ops[1].sem_num = 0;
      sem_ops[1].sem_op = 1;
      sem_ops[1].sem_flg = SEM_UNDO;
      //full -1
      sem_ops[2].sem_num = 3;
      sem_ops[2].sem_op = -1;
      sem_ops[2].sem_flg = 0;
      //operations
      ret_val = semop( sem_id, &sem_ops[0], 3);
      if( ( ret_val != 0) && ( errno == EAGAIN ) )
      {
        printf("%s: sender crashed\n", argv[0] );
        exit(-1);
      }

      write_amount = write( 1, shm_adr -> buf, shm_adr -> amount);

      //empty +1
      sem_ops[0].sem_num = 2;
      sem_ops[0].sem_op = 1;
      sem_ops[0].sem_flg = SEM_UNDO;
      //operations
      ret_val = semop( sem_id, &sem_ops[0], 1);
      printf("\n\nwrite_amount = %d\n", write_amount);
    } while ( write_amount == BUF_SIZE );
    printf("\n\nexit from while\n");
    //ending
    shmdt( shm_adr );
    printf("\n\nready to rm\n\n");
    shmctl( shm_id, IPC_RMID, NULL );
    semctl( sem_id, 0, IPC_RMID, NULL );
    exit(0);
  }
}
Пример #9
0
Share *
new_share( key_t key, int segment_size, int flags ) {
  Share *share;
  Node *node;
  int semid;
  struct shmid_ds shmctl_arg;
  SEMUN semun_arg;

again:
  if ( ( semid = semget( key, 3, flags ) ) < 0 ) {
    LOG1( "semget failed (%d)", errno );
    return NULL;
  }

  /* It's possible for another process to obtain the semaphore, lock it, *
   * and remove it from the system before we have a chance to lock it.   *
   * In this case (EINVAL) we just try to create it again.               */
  if ( GET_EX_LOCK( semid ) < 0 ) {
    if ( errno == EINVAL ) {
      goto again;
    }
    LOG1( "GET_EX_LOCK failed (%d)", errno );
    return NULL;
  }

  /* XXX IS THIS THE RIGHT THING TO DO? */
  if ( segment_size <= sizeof( Header ) ) {
    segment_size = SHM_SEGMENT_SIZE;
  }

  Newxz( node, 1, Node );

  if ( ( node->shmid = shmget( key, segment_size, flags ) ) < 0 ) {
    LOG1( "shmget failed (%d)", errno );
    return NULL;
  }

  if ( ( node->shmaddr =
         ( Header * ) shmat( node->shmid, ( char * ) 0,
                             0 ) ) == ( Header * ) - 1 ) {
    LOG1( "shmat failed (%d)", errno );
    return NULL;
  }

  node->next = NULL;

  Newxz( share, 1, Share );

  share->key = key;
  share->next_key = key + 1;
  share->flags = flags;
  share->semid = semid;
  share->lock = 0;
  share->head = node;
  share->tail = node;

  /* is this a newly created segment?  if so, initialize it */
  if ( ( semun_arg.val =
         semctl( share->semid, 0, GETVAL, semun_arg ) ) < 0 ) {
    LOG1( "shmctl failed (%d)", errno );
    return NULL;
  }

  if ( semun_arg.val == 0 ) {
    semun_arg.val = 1;
    if ( semctl( share->semid, 0, SETVAL, semun_arg ) < 0 ) {
      LOG1( "shmctl failed (%d)", errno );
      return NULL;
    }
    share->head->shmaddr->length = 0;
    share->head->shmaddr->next_shmid = -1;
    share->head->shmaddr->shm_state = 1;
    share->head->shmaddr->version = 1;
  }

  share->shm_state = share->head->shmaddr->shm_state;
  share->version = share->head->shmaddr->version;

  /* determine the true length of the segment.  this may disagree *
   * with what the user requested, since shmget() calls will      *
   * succeed if the requested size <= the existing size           */
  if ( shmctl( share->head->shmid, IPC_STAT, &shmctl_arg ) < 0 ) {
    LOG1( "shmctl failed (%d)", errno );
    return NULL;
  }

  share->segment_size = shmctl_arg.shm_segsz;
  share->data_size = share->segment_size - sizeof( Header );

  if ( RM_EX_LOCK( semid ) < 0 ) {
    LOG1( "RM_EX_LOCK failed (%d)", errno );
    return NULL;
  }

  return share;
}
Пример #10
0
int
main(void) {
	char buff[100];
	channel = (void *)malloc(200);
	
	/*---Establezco los canales de comunicacion---*/
	getDefaultChannel(channel);
	if ( connectToChannel(channel,CLIENT) < 0 ) {
		printf("Server not available\n");
		return 0;
	}
	itoa(buff,GET_CHANNEL);
	sendPacket(buff,strlen(buff)+1, channel, CLIENT);
	receivePacket(buff,MAX_SIZE, channel, CLIENT);
	disconnectFromChannel(channel);
	stringToChannel(buff, channel);
	connectToChannel(channel,CLIENT);

	/*---Abro el pipe de sincronismo entre padre e hijo---*/
	if( pipe(syncPipe) == -1 ){
		printf("Error al crear el pipe de sincronismo en el client.\n");
		return 0;
	}
	
	/*---Abro el pipe de pasaje de argumentos para seniales---*/
	if( pipe(signalPipe) == -1 ){
		printf("Error al crear el pipe de args para seniales.\n");
		return 0;	
	}
	
	/*---Seteo el semaforo---*/
	int semkey = getpid();
	semun x;
	x.val = 1;
	int flags = IPC_CREAT | IPC_EXCL;
	if ( ( semid = semget(semkey, 1, 0666 | flags )) == -1 ) {
		printf("Error al crear semaforo: %d\n", semkey);
		return -1;
	}
	if ( semctl(semid, 0, SETVAL, x) == -1 ) {
		printf("Error al configurar semaforo\n");
		return -1;
	}
	/*---Configuracion de manejo de seniales---*/
	/* SIGUSR1 -> SHELL_SIGNAL */
	/* SIGUSR2 -> DRAFT_SIGNAL */
	struct sigaction draftSigAct;
	draftSigAct.sa_handler = draftSignalHandler;
	sigemptyset(&(draftSigAct.sa_mask));
	draftSigAct.sa_flags = SA_NODEFER;
	struct sigaction shellSigAct;
	shellSigAct.sa_handler = shellSignalHandler;
	sigemptyset(&(shellSigAct.sa_mask));
	shellSigAct.sa_flags = SA_NODEFER;
	sigaction( SIGUSR1, &shellSigAct, NULL);
	sigaction( SIGUSR2, &draftSigAct, NULL);
	static struct sigaction act3;
	act3.sa_handler = catchSigPipe;
	sigfillset(&(act3.sa_mask));
	sigaction(SIGPIPE, &act3, NULL);
	static struct sigaction act1;
	static struct sigaction act2;

	
	/*Convenimos a este proceso como programa de envio de datos*/
	senderPid = getpid();
	pid_t auxPid;
	
	switch( auxPid = fork() ) {
		case -1:
			printf("Error al configurar el cliente.\n");
			break;
		case 0:
			receiverPid = getpid();
			close(syncPipe[0]); 
			close(signalPipe[0]);
			receive();
			break;
		default:
	
			act1.sa_handler = shutDown;
			sigfillset(&(act1.sa_mask));
			sigaction(SIGINT, &act1, NULL);
			act2.sa_handler = shutDown;
			sigfillset(&(act2.sa_mask));
			sigaction(SIGTSTP, &act2, NULL);
			receiverPid = auxPid;
			close(signalPipe[1]);
			close(syncPipe[1]);
			raise(SIGUSR1);break;
	}	
	return 0;
}
Пример #11
0
Файл: 2.c Проект: aqxin/xx
int main(int argc, char *argv[])
{
	// 创建虚拟主存
	int *buf = (int*)mmap(NULL, sizeof(int)*MAXSEM, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);

	int times = MAXSEM;
	if (2 == argc)
		times = atoi(argv[1]);

	// 获得信号量的描述符
	full_id  = semget(IPC_PRIVATE, 3, IPC_CREAT|0666);
	empty_id = semget(IPC_PRIVATE, 3, IPC_CREAT|0666);
	mutx_id  = semget(IPC_PRIVATE, 1, IPC_CREAT|0666);

	// 初始化P,V操作;
	arg.val = 0;
	semctl(full_id, 0, SETVAL, arg);
	semctl(full_id, 1, SETVAL, arg);
	semctl(full_id, 2, SETVAL, arg);
	arg.val = 1;
	semctl(empty_id, 0, SETVAL, arg);
	semctl(empty_id, 1, SETVAL, arg);
	semctl(empty_id, 2, SETVAL, arg);
	semctl(mutx_id, 0, SETVAL, arg);

	p[0].sem_num = 0;
	v[0].sem_num = 0;
	p[1].sem_num = 1;
	v[1].sem_num = 1;
	p[2].sem_num = 2;
	v[2].sem_num = 2;

	p[0].sem_op = -1;
	v[0].sem_op = 1;
	p[1].sem_op = -1;
	v[1].sem_op = 1;
	p[2].sem_op = -1;
	v[2].sem_op = 1;

	p[0].sem_flg = v[0].sem_flg = SEM_UNDO;
	p[1].sem_flg = v[1].sem_flg = SEM_UNDO;
	p[2].sem_flg = v[2].sem_flg = SEM_UNDO;

	P.sem_op = -1;
	V.sem_op = 1;
	P.sem_flg = V.sem_flg = SEM_UNDO;
	P.sem_num = V.sem_num = 0;


//	Init_sem();

	// 消费者1进程
	if (fork() == 0) {
		int i, message;
		printf("child 1 process(PID=%d) is running.\n", getpid());
		for (i=0; i<times; i++) {
			// 申请数据;
			semop(full_id, &p[0], 1);
			// 申请对缓冲区的互斥操作
			semop(mutx_id, &P, 1);
			message = buf[0];
			buf[0] = 0;
			printf("child 1 PID=%d) get message:%d.\n", getpid(), message);
			// 释放对缓冲区的互斥操作
			semop(mutx_id, &V, 1);
			// 释放申请数据
			semop(empty_id, &v[0], 1);
		}
		printf("child 1 process(PID=%d) is over.\n", getpid());	
		exit(0);
	}

	// 消费者2进程
	if (fork() == 0) {
		int i, message;
		printf("child 2 process(PID=%d) is running.\n", getpid());
		for (i=0; i<times; i++) {
			// 申请数据
			semop(full_id, &p[1], 1);
			// 申请对缓冲区的互斥操作
			semop(mutx_id, &P, 1);
			message = buf[1];
			buf[1] = 0;
			printf("child 2 PID=%d) get message:%d.\n", getpid(), message);
			// 释放对缓冲区的互斥操作
			semop(mutx_id, &V, 1);
			// 释放申请数据;
			semop(empty_id, &v[1], 1);
		}
		printf("child 2 process(PID=%d) is over.\n", getpid());	
		exit(0);
	}

	// 消费者3进程
	if (fork() == 0) {
		int i, message;
		printf("child 3 process(PID=%d) is running.\n", getpid());
		for (i=0; i<times; i++) {
			// 申请数据
			semop(full_id, &p[2], 1);
			// 申请对缓冲区的互斥操作
			semop(mutx_id, &P, 1);
			message = buf[2];
			buf[2] = 0;
			printf("child 3 PID=%d) get message:%d.\n", getpid(), message);
			// 释放对缓冲区的互斥操作
			semop(mutx_id, &V, 1);
			// 释放申请数据
			semop(empty_id, &v[2], 1);
		}
		printf("child 3 process(PID=%d) is over.\n", getpid());	
		exit(0);
	}

	// 生产者进程
	int i, j;
	printf("parent process(PID=%d) is running.\n", getpid());
	for (i=0; i<times; i++) {
		// 申请空闲缓冲区3快
		semop(empty_id, p, 3);
		// 申请对缓冲区的互斥操作
		semop(mutx_id, &P, 1);
		// 将数据写入缓冲区
		for (j=0;j<MAXSEM;++j) {
			buf[j] = i+1;
		}
		printf("parent (PID=%d) product message:%d.\n", getpid(), i+1);
		// 释放对缓冲区的互斥操作
		semop(mutx_id, &V, 1);
		// 释放空闲缓冲区3块
		semop(full_id, v, 3);
	}
	printf("parent process(PID=%d) is over.\n", getpid());
	
	sleep(1);
	return 0;
}
Пример #12
0
void ipc_systemv_sem()
{
	int semid;
	key_t key;
	const unsigned int perms = S_IRUSR | S_IWUSR | S_IWGRP; // 읽기/쓰기 권한이 있어야 함.
	struct semid_ds ds;

	key = ftok(KEY_PATH, 1);

	// 세마포어의 갯수가 1개인(0번) 세마포어 집합을 생성한다.
	semid = semget(key, 1, IPC_CREAT | IPC_EXCL | perms);
/*
	세마포어에 접근하는 프로세스 중 세마포어를 생성하는 프로세스는 1개이다.
	나머지 프로세스는 여기서 EEXIST 에러를 리턴받고 else로 가서 이미 생성된 세마포어에 접근하게 됨.
*/
	if(semid != -1) {
		union semun arg;
		struct sembuf sop;

		// 0번 세마포어 값을 0으로 설정
		arg.val = 0;
		if(semctl(semid, 0, SETVAL, arg) == -1)
			errExit("semctl()");
/*
		sem_op = 0의 값으로 semop을 호출하는 것은 세마포어 값이 0이 될때까지 블록한다는 의미이다.
		그런데 이미 세마포어의 값이 0으로 초기화되기 때문에 no-op에 해당한다.
		하지만 semop 호출은 sem_optime(접근 시간)을 변경해서
		뒤이어 실행되는 다른 프로세스가 세마포어가 초기화되었음을 알 수 있게 한다.
*/
		sop.sem_num = 0; // 세마포어 번호 0에 대해서,
		sop.sem_op = 0; // 세마포어 값은 이미 0이므로 아무 작업도 이루어지지 않는다.
		sop.sem_flg = 0;
		if(semop(semid, &sop, 1) == -1) {
			errExit("semop()");
		} // 이 때 sem_optime이 업데이트됨.

		// 0번 세마포어 값을 2로 설정.
		// 따라서 세마포어 값이 1, 2일 때 프로세스들은 '작업'으로 진입할 수 있다.
		arg.val = 2;
		if(semctl(semid, 0, SETVAL, arg) == -1)
			errExit("semctl()");
	}
	// key에 해당하는 세마포어 식별자가 이미 생성되어 있는 경우,
	else {
		const int MAX_TRIES = 10;
		int j;
		union semun arg;
		// 이미 열려진 세마포어 식별자를 얻어옴.
		if((semid = semget(key, 1, perms)) == -1)
			errExit("semget()");

		arg.buf = &ds;
		// 세마포어를 생성하는 프로세스가 semop를 호출할 때까지 대기
		for (j = 0; j < MAX_TRIES; ++j) {
			if(semctl(semid, 0, IPC_STAT, arg) == -1)
				errExit("semctl()");
			// 세마포어 생성이 완료되었다면, 루프 종료
			if(ds.sem_otime != 0)
				break;
			sleep(1);
		}
	}

	if(ds.sem_otime == 0)
		fatal("Semaphore not initialized yet.");

	// 0번 세마포어 값 조회
	int semval = semctl(semid, 0, GETVAL, 0);
	printf("val = %d\n", semval);

	// 세마포어 값을 -1한다. -1이 가능할 때까지 대기함.
	struct sembuf sop;
	sop.sem_num = 0;
	sop.sem_op = -1;
	sop.sem_flg = 0;
	if(semop(semid, &sop, 1) == -1) {
		errExit("semop()");
	}
/*
	여기서 만일 semop에 의해 블록되고 있는 상태에서 SIGINT등을 받아서 블록이 중단되면,
	세마포어를 해제하는 작업이 수행되지 않기 때문에, 다른 프로세스들이 영원히 진입할 수 없는 문제가 생김.
*/
	// 세마포어로 보호해야 하는 '작업'을 수행
	printf("job start..\n");
	sleep(5);
	printf("job end..\n");


	// 세마포어 값을 +1한다. 세마포어에 대기하고 있는 다른 프로세스들이 '작업'으로 진입한다.
	sop.sem_num = 0;
	sop.sem_op = 1;
	sop.sem_flg = 0;
	if(semop(semid, &sop, 1) == -1) {
		errExit("semop()");
	}


}
Пример #13
0
int main()
{
    int running = 1;
    void *shared_memory = (void *)0;
    struct shared_use_st *shared_stuff;
    int shmid;

    srand((unsigned int)getpid());

	//get the semaphores	

    sem_id = semget((key_t)1233, 1, 0666 | IPC_CREAT);
    sem_id2 = semget((key_t)1235, 1, 0666 | IPC_CREAT);
    sem_id3 = semget((key_t)1236, 1, 0666 | IPC_CREAT);

/*
*sets the semaphores to the required values if it fails program ends
*/
    
	if (!set_mutex()| !set_available()| !set_empty()) {
            fprintf(stderr, "Failed to initialize semaphore\n");
            exit(EXIT_FAILURE);
        }

	//get shared memory

    shmid = shmget((key_t)1231, (sizeof(struct shared_use_st)- sizeof(int)) , 0666 | IPC_CREAT);

    if (shmid == -1) {
        fprintf(stderr, "shmget failed prod\n");
        exit(EXIT_FAILURE);
    }

/* We now make the shared memory accessible to the program. */

    shared_memory = shmat(shmid, (void *)0, 0);
    if (shared_memory == (void *)-1) {
        fprintf(stderr, "shmat failed\n");
        exit(EXIT_FAILURE);
    }

    printf("Memory attached at %X\n", (void *)shared_memory);

/* The next portion of the program assigns the shared_memory segment to shared_stuff,
 Reads in from the input file test4k.txt into the buffer ibuffer string of size BUFSIZ, then the 
 loop continually copies text from ibuffer into the buffers in shared memory which take 128 bytes of char until a value less than 128 is written which means approached end of text then it sleeps and deletes the semaphores */

    shared_stuff = (struct shared_use_st *)shared_memory;
    //shared_stuff->written_by_you = 0;

    char ibuffer[BUFSIZ];   // input buffer 
 
    int in; // variable to hold reference to input file
    int index=0; // current index of element in array of structs in shared memory 
    int len;  // length read 
     int tot = 0; // Total length read

    in = open("test4k.txt",O_RDONLY);
   
	len = read(in,ibuffer, sizeof(ibuffer));
    while(running){
	
	for(int i = 0; i<= len; i+=128){
		sleep(2);
		if((len-i)<128){

		//if value written is less than 128  delete semaphores


		shared_stuff->msgs[index].written = len-i;
		memcpy(shared_stuff->msgs[index].some_text, ibuffer + (len-i), (len-i));
		tot+= shared_stuff->msgs[index].written;
		printf("Producer: bytes written val %d\n", shared_stuff->msgs[index].written);

		printf("Producer: Total bytes written val %d\n", tot);		

		sleep(10);
		del_semvalue();
		exit(EXIT_SUCCESS);
		
		}
		else{
		empty_p();	
		mutex_p();

 		shared_stuff->msgs[index].written = 128;
		
		printf("Producer: bytes written val %d\n", shared_stuff->msgs[index].written);
		memcpy(shared_stuff->msgs[index].some_text,ibuffer + i,128);		
		tot+= shared_stuff->msgs[index].written;
		
		index = (index+1)%k;  
		mutex_v();
		available_v();
		
		}
	}
   }
  

/* Lastly, the shared memory is detached and then deleted. */

    if (shmdt(shared_memory) == -1) {
        fprintf(stderr, "shmdt failed\n");
        exit(EXIT_FAILURE);
    }

    if (shmctl(shmid, IPC_RMID, 0) == -1) {
        fprintf(stderr, "shmctl(IPC_RMID) failed\n");
        exit(EXIT_FAILURE);
    }

	

    exit(EXIT_SUCCESS);
}
Пример #14
0
main()
{
	semid=semget(IPC_PRIVATE, 3, 0666);
	
	seminfo.val=1;
	semctl(semid,C_C, SETVAL,seminfo);
	
	seminfo.val=0;
	semctl(semid,C_D, SETVAL,seminfo);

	shmid=shmget(IPC_PRIVATE, 2, 0666);//for storing command and port
	shmid_s =shmget(IPC_PRIVATE, 100, 0666);//for storing file name
	
	shmptr=(int *)shmat(shmid, 0, 0);
	shmptr_s=(char *)shmat(shmid_s, 0, 0);

	*(shmptr)=0;
	*(shmptr+1)=0;

	
	int cc = getpid();
	int cd = fork();
	int d= 4;
	int32_t conv;
	int code;
	
	//Control Process of Client
	if(getpid() == cc)
	{
		
		//printf("In CC...");
		int tcpC1 ;
		struct sockaddr_in serv_addr;
		int i;
		char buf[100];
		
		
		//Socket Creation
		if ((tcpC1 = socket(AF_INET, SOCK_STREAM, 0)) < 0) 
		{
			printf("Unable to create socket\n");
			exit(0);
		}

		//Initialing the socket variables
		serv_addr.sin_family= AF_INET;
		serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
		serv_addr.sin_port=htons(50000);

		//Connecting to server
		if ((connect(tcpC1, (struct sockaddr *) &serv_addr,sizeof(serv_addr))) < 0) 
		{
			printf("Unable to connect to server\n");
			exit(0);
		}	
		
		for(i=0;i<100;i++)
			buf[i]='\0';
		
		while(1)
		{
			semop(semid,&WaitC,1);
			printf(">");
			fgets(buf,100,stdin);
			write(tcpC1, buf, strlen(buf) + 1);//sending command to server
			
			int k =0,index =0;
			char a[100],b[100];

			while(1)
			{
				if(buf[k]==' ' || buf[k]=='\0')
					break;
				else
				{
					a[index]=buf[k];
					index++;
				}
				k++;
			}
			a[index]='\0';//command saved
			
			k++;
                   	index=0;
                   	
			while(1)
			{  
				if((strcmp(a,"quit")==0) || buf[k]=='\0')
					break;
				else
				{
					b[index]=buf[k];
					index++;
				}
				k++;
			}
			b[index]='\0';//argument saved

			int flag = 0;
			
			//port command received and port number stored
			if(strcmp(a,"port")==0)
			{
				*(shmptr)=atoi(b);
				semop(semid,&StartC,1);
				flag = 1;
			}
			//cd command received
			else if(strcmp(a,"cd")==0)
			{
				semop(semid,&StartC,1);
				flag=2;
			}
			//get command received and file name stored		
			else if(strcmp(a,"get")==0)
			{
				shmptr=(int *)shmat(shmid, 0, 0);
				*(shmptr + 1) = 0;

				shmptr_s=(char *)shmat(shmid_s, 0, 0);
				int len = strlen(b);
				char filename[100];
				index = 0;
				for(i=0;i<len;i++)
				{
					if(b[i]=='/')
						index=0;
					else
					{
						filename[index]=b[i];
						index++;
					}		
				}
				filename[index]='\0';
				strcpy(shmptr_s,filename);

				read(tcpC1,&conv,sizeof(conv));
				code = ntohl(conv);
				if(code == ERROR_BAD_FILE)
				{	
					printf("%d Bad file error!\n",code);
					semop(semid,&StartC,1);
					continue;
				}
				else if(code == ERROR_EXTRA_ARGUMENTS)
				{	
					printf("%d Extra arguments!\n",code);
					semop(semid,&StartC,1);
					continue;
				}
				semop(semid,&StartD,1);
				continue;
			}
			//put command received and file name stored
			else if(strcmp(a,"put")==0)
			{
				//printf("put received");
				shmptr=(int *)shmat(shmid, 0, 0);
				*(shmptr + 1) = 1;

				shmptr_s=(char *)shmat(shmid_s, 0, 0);
				strcpy(shmptr_s,b);
				read(tcpC1,&conv,sizeof(conv));
				code = ntohl(conv);
				if(code == RIGHT_COMMAND)
				{
					
					int len = strlen(b);
					b[len-1]='\0';
					FILE *f = fopen(b,"r");
					if(f == NULL)
						code = ERROR_BAD_FILE;
					conv = htonl(code);	
					write(tcpC1,&conv,sizeof(conv));
	
				}
				if(code == ERROR_BAD_FILE)
				{	
					printf("%d Bad file error!\n",code);
					fflush(stdout);
					semop(semid,&StartC,1);
					continue;
				}
				else if(code == ERROR_EXTRA_ARGUMENTS)
				{	
					printf("%d Extra arguments!\n",code);
					semop(semid,&StartC,1);
					continue;
				}
				semop(semid,&StartD,1);
				continue;
			}
				
			read(tcpC1,&conv,sizeof(conv));
			code = ntohl(conv);
			//codes checking

			if(code == WRONG_START_COMMAND)
			{	
				printf("%d Wrong Start command!\n",code);
				exit(0);
			}
			else if(code == RIGHT_COMMAND)
			{
				printf("%d Command executed successfully!\n",code);
			}
			else if(code == ERROR_START_COMMAND)
			{
				printf("%d Error in Start command!\n",code);
				exit(0);
			}
			else if(code == ERROR_DIRECTORY_COMMAND && flag==2)
			{
				printf("%d Wrong Directory change command!\n",code);
			}
			else if(code == EXIT_COMMAND)
			{
				printf("%d Client exiting!\n",code);
				close(tcpC1);
				shutdown(tcpC1,SHUT_WR);
				exit(0);
			}
			else if(code == ERROR_BAD_COMMAND)
			{
				printf("%d Command does not exist!\n",code);
				fflush(stdout);
				semop(semid,&StartC,1);
			}
			else if(code == ERROR_EXTRA_ARGUMENTS)
			{
				printf("%d Extra arguments!\n",code);
				fflush(stdout);
				semop(semid,&StartC,1);
				if(flag == 1)
					exit(0);
			}
							
		}	
	}
	//Data process of client
	else
	{
		cd = getpid();
		while(1)
		{
			semop(semid,&WaitD,1);

			int tcpC2,newtcpC2,clilen;
			char buf[100];
			char buffer[100],last[2],c;
			int num, len;
			struct sockaddr_in serv_addr,clientAddr;

			shmptr=(int *)shmat(shmid, 0, 0);
			int port = *(shmptr);
			int command = *(shmptr + 1);

			shmptr_s=(char *)shmat(shmid_s, 0, 0);
			strcpy(buf,shmptr_s);
			len = strlen(buf);
			buf[len-1]='\0';
			//printf("%s....file",buf);
			
			refresh(port);

			if ((tcpC2 = socket(PF_INET, SOCK_STREAM, 0)) < 0) 
			{
				printf("Unable to create socket\n");
				exit(0);
			}
			
			//Initializing the socket variables
			serv_addr.sin_family= AF_INET;
			serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
			serv_addr.sin_port=htons(port);
		
			//Binding the TCP socket
			if (bind(tcpC2, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) 
			{
				printf("Unable to bind local address\n");
				exit(0);
			}
		
			//Listening to 5 calls
			listen(tcpC2, 5);

			newtcpC2 = accept(tcpC2, (struct sockaddr *) &clientAddr,&clilen) ;
			if (newtcpC2 < 0)
			{
				printf("Accept error C2\n");
				exit(0);
			}
			//if get received
			if(command == 0)
			{
				FILE *f;
				f=fopen(buf,"w");
				while(1)
				{
					for(i=0;i<100;i++)
						buffer[i]='\0';
					for(i=0;i<2;i++)
						last[i]='\0';
					read(newtcpC2,last,2);
					read(newtcpC2,&num,sizeof(num));
					len = ntohl(num);
					read(newtcpC2,buffer,100);
					fprintf(f,"%s",buffer);
					//printf("%s..",last);
					if(last[0]=='L')
						break;
					
				}
				code = RIGHT_FILE_TRANSFER;
				if(code == RIGHT_FILE_TRANSFER)
				{	
					printf("%d File transfered successfully!\n",code);
					fflush(stdout);
				}
				fclose(f);
			}
			//if put received
			else if(command ==1)
			{ 
	
				FILE *f;
				f=fopen(buf,"r");
				while(1)
				{
					len = 0;
					for(i=0;i<100;i++)
						buffer[i]='\0';
					for(i=0;i<2;i++)
						last[i]='\0';
					while(len<99 && (c = fgetc(f))!= EOF)
					{
					
						buffer[len]=c;
						len++;
						
					}
					buffer[len]='\0';
					if(len<99)
						last[0]='L';
					else
						last[0]='A';
					last[1]='\0';
					write(newtcpC2,last,2);
					int32_t num = htonl(len);
					write(newtcpC2,&num,sizeof(num));
					write(newtcpC2,buffer,strlen(buffer)+1);
					//printf("%s  ",last);
					//printf("%s ",buffer);
					//printf("%d\n",len);
					if(len<99)
					{
						
						break;					
					}
				}
				int code = RIGHT_FILE_TRANSFER;
				if(code == RIGHT_FILE_TRANSFER)
				{	
					printf("%d File transfered successfully!\n",code);
					fflush(stdout);
				}
				fclose(f);
                	      
			}	
			sleep(1);
			close(newtcpC2);
			shutdown(newtcpC2, SHUT_WR); 
			close(tcpC2);
			shutdown(tcpC2, SHUT_WR); 
			//printf("Closing...");
			//fflush(stdout);
			semop(semid,&StartC,1);
		}
	}	

}
Пример #15
0
int Linda::init(key_t shm_key)
{
    // try to create new shared memory segment
    shmId = shmget(shm_key, 4 + MAX_TUPLES*(TUPLE_MAX_SIZE + 1), IPC_CREAT | IPC_EXCL | 0777);

    // try to create new shared memory segment
    shmId = shmget(shm_key, 4 + MAX_TUPLES*(TUPLE_MAX_SIZE + 1), IPC_CREAT | IPC_EXCL | 0777);

    if (shmId < 0 && errno == EEXIST) // someone already created shm segment
    {
        // connect to existing shm segment
        shmId = shmget(shm_key, 4 + MAX_TUPLES*(TUPLE_MAX_SIZE + 1), IPC_CREAT | 0777);
        if(shmId == -1)
        {
            int err = errno;
            if (debug) std::cerr << "[Linda] Error connecting to shared memory segment." << std::endl;
            return err;
        }

        // read basic environment data (process counter and semaphores' table id)

        if ((shm = (SharedMemory*)shmat(shmId, 0, 0)) < 0)
        {
            int err = errno;
            if (debug) std::cerr << "[Linda] Error mapping shared memory segment." << std::endl;
            return err;
        }
        if (debug) std::cout << "[Linda] semKey=" << shm->semKey;
        if ((semId = semget(shm->semKey, 3, IPC_CREAT | 0777)) == -1)
        {
            int err = errno;
            if (debug) std::cerr << "[Linda] Error obtaining existing semaphores." << std::endl;
            return errno;
        }
        if (debug) std::cout << "[Linda] semId="<<semId << std::endl;

        struct sembuf getCriticalSection[1] = 
        {
            SEM_READ, 1, 0,
        };
        if (semop(semId, getCriticalSection, sizeof(getCriticalSection)/sizeof(sembuf)) < 0)
        {
            int err = errno;
            if (debug) 
                std::cerr << "[Linda input] Error refreshing readers' semaphore limit." << std::endl;
            return err;
        }

        return 0;
    }
    else if (shmId == -1)
    {
        int err = errno;
        if (debug) 
            std::cerr << "[Linda] Error creating new shared memory segment." << std::endl;
        return err;
    }

    // we created new shared memory segment, so fill it with empty environment data

    if ((long)(shm = (SharedMemory*)shmat(shmId, 0, 0)) < 0)
    {
        int err = errno;
        if (debug) 
            std::cerr << "[Linda] Error mapping shared memory segment." << std::endl;
        return err;
    }

    int key = 1234;

    if ((semId = semget(key, 3, IPC_CREAT | IPC_EXCL | 0777))  == -1)
    {
        int err = errno;
        if (debug) 
            std::cerr << "[Linda] Error creating semaphore set." << std::endl;
        return err;
    }
    if (debug) 
        std::cout << "[Linda] semId=" << semId << std::endl;

    shm->semKey = key;

    for (int i = 0; i < MAX_TUPLES; i++) 
        shm->tupleArray[i].valid = TUPLE_INVALID;

    struct sembuf increment[1] = 
    {
        SEM_READ, 1, 0,
    };
    if (semop(semId, increment, sizeof(increment)/sizeof(sembuf)) < 0)
    {
        int err = errno;
        if (debug) 
            std::cerr << "[Linda input] Error refreshing readers' semaphore limit." << std::endl;
        return err;
    }
    if (debug) 
        std::cout<<"[Linda] Incremented sem_read"<<std::endl;
    return 0;
}
Пример #16
0
Файл: bus.c Проект: uselessd/bus
/**
 * Remove the semaphore array for the bus
 * 
 * @param   bus  Bus information
 * @return       0 on success, -1 on error
 */
static int
remove_semaphores(const bus_t *bus)
{
	int id = semget(bus->key_sem, BUS_SEMAPHORES, 0);
	return ((id == -1) || (semctl(id, 0, IPC_RMID) == -1)) ? -1 : 0;
}
Пример #17
0
PR_IMPLEMENT(PRSem *) PR_OpenSemaphore(
    const char *name,
    PRIntn flags,
    PRIntn mode,
    PRUintn value)
{
    PRSem *sem;
    key_t key;
    union semun arg;
    struct sembuf sop;
    struct semid_ds seminfo;
#define MAX_TRIES 60
    PRIntn i;
    char osname[PR_IPC_NAME_SIZE];

    if (_PR_MakeNativeIPCName(name, osname, sizeof(osname), _PRIPCSem)
        == PR_FAILURE)
    {
        return NULL;
    }

    /* Make sure the file exists before calling ftok. */
    if (flags & PR_SEM_CREATE)
    {
        int osfd = open(osname, O_RDWR|O_CREAT, mode);
        if (-1 == osfd)
        {
            _PR_MD_MAP_OPEN_ERROR(errno);
            return NULL;
        }
        if (close(osfd) == -1)
        {
            _PR_MD_MAP_CLOSE_ERROR(errno);
            return NULL;
        }
    }
    key = ftok(osname, NSPR_IPC_KEY_ID);
    if ((key_t)-1 == key)
    {
        _PR_MD_MAP_DEFAULT_ERROR(errno);
        return NULL;
    }

    sem = PR_NEW(PRSem);
    if (NULL == sem)
    {
        PR_SetError(PR_OUT_OF_MEMORY_ERROR, 0);
        return NULL;
    }

    if (flags & PR_SEM_CREATE)
    {
        sem->semid = semget(key, 1, mode|IPC_CREAT|IPC_EXCL);
        if (sem->semid >= 0)
        {
            /* creator of a semaphore is responsible for initializing it */
            arg.val = 0;
            if (semctl(sem->semid, 0, SETVAL, arg) == -1)
            {
                _PR_MD_MAP_DEFAULT_ERROR(errno);
                PR_DELETE(sem);
                return NULL;
            }
            /* call semop to set sem_otime to nonzero */
            sop.sem_num = 0;
            sop.sem_op = value;
            sop.sem_flg = 0;
            if (semop(sem->semid, &sop, 1) == -1)
            {
                _PR_MD_MAP_DEFAULT_ERROR(errno);
                PR_DELETE(sem);
                return NULL;
            }
            return sem;
        }

        if (errno != EEXIST || flags & PR_SEM_EXCL)
        {
            _PR_MD_MAP_DEFAULT_ERROR(errno);
            PR_DELETE(sem);
            return NULL;
        }
    }

    sem->semid = semget(key, 1, NSPR_SEM_MODE);
    if (sem->semid == -1)
    {
        _PR_MD_MAP_DEFAULT_ERROR(errno);
        PR_DELETE(sem);
        return NULL;
    }
    for (i = 0; i < MAX_TRIES; i++)
    {
        arg.buf = &seminfo;
        semctl(sem->semid, 0, IPC_STAT, arg);
        if (seminfo.sem_otime != 0) break;
        sleep(1);
    }
    if (i == MAX_TRIES)
    {
        PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
        PR_DELETE(sem);
        return NULL;
    }
    return sem;
}
Пример #18
0
Файл: sem1.c Проект: beatyou/APP
int main(int argc, char const *argv[])
{
	//得到键值
	key_t key = ftok("sem1.c",0x1234);
	if(key == -1)
	{
		perror("ftok");
		exit(-1);
	}

	//创建信号量
	int semid = semget(key,1,IPC_CREAT|IPC_EXCL);
	if(semid == -1)
	{
		perror("semget");
		exit(-1);
	}

	//初始化信号量
	semctl(semid,0,SETVAL,3);

	//进程操作和pv操作
	pid_t pid = fork();
	if(pid < 0)
	{
		perror("fork");
		exit(-1);
	}

	//子进程进行p操作 -1
	if(pid == 0)
	{
		struct sembuf sem;
		while(1)
		{
			sem.sem_num = 0;	//第几个信号量
			sem.sem_op = -1;	//p操作
			sem.sem_flg = 0;	//堵塞

			semop(semid,&sem,1);
			printf("child process is running\n");
		}
	}

	//父进程进行v操作 +1
	if(pid > 0)
	{
		sleep(2);
		struct sembuf sem;
		while(1)
		{
			sem.sem_num = 0;	//第几个信号量
			sem.sem_op = +1;	//v操作
			sem.sem_flg = 0;	//堵塞

			semop(semid,&sem,1);
			printf("parent process is running\n");
			sleep(1);
		}
	}
	//删除信号量
	semctl(semid,0,IPC_RMID);
	return 0;
}
Пример #19
0
int main (int argc, char *argv[]){
    
    //Print user info
    printf("\nAuthor : Bresia Prudente\n"
           "ACCC ID: bprude2\n\n");
    
    /**********************/
    /* PARSE COMMAND LINE */
    /**********************/
    if (argc < 7 && argc < 5) {
        printf("Usage: ./raceTest nBuffers nWorkers sleepMin sleepMax [randSeed] [-lock | -nolock]\n\n");
        exit(-1);
    }//end if
    
    //Declare and initialize variables
    int nBuffers = atoi(argv[1]);
    int nWorkers = atoi(argv[2]);
    float sleepMin = atof(argv[3]);
    float sleepMax = atof(argv[4]);
    int randSeed;
    double randomized;
    bool semLock = FALSE;
    int semid;
    int bufArr[nBuffers];  //local array initialized to zero
    double nWorkerArr[nWorkers];    //for sorting array of rand numbers

    //initializing local array
    int tmp1;
    for (tmp1 = 0; tmp1 < nBuffers; tmp1++){
        bufArr[tmp1] = 0;
    }//end for

    printf("Running simulation for %d workers accessing %d buffers, ", nWorkers, nBuffers);
    
    //Check if user enables lock or nolock
    if (argc == 7) {
        if (strcmp(argv[6], "-lock") == 0) {
            semLock = TRUE;
            printf("with locking.\n");   //sanity test
        }//end if
        else if (strcmp(argv[6], "-nolock") == 0){
            semLock = FALSE;
            printf("without locking.\n");    //sanity test
        }//end else if
    }//end if
    //if user doesn't enter a value, default to unlock
    if (argc < 7){
        semLock = FALSE;
        printf("without locking (default).\n");   //sanity test
    }//end if
    
    //Min and Max must be positive real numbers
    //min cannot be greater than max
    if (sleepMin > sleepMax) {
        printf("sleepMin cannot be greater than sleepMax!\n\n");
        exit(-1);
    }//end if
    else if((sleepMin < 0) || (sleepMax < 0)){
        printf("sleepMin and/or sleepMax values must be POSITIVE\n\n");
        exit(-1);
    }//end else if

    printf("Sleeping from %f to %f seconds.\n", sleepMin, sleepMax);
    
    //To check randSeed
    if (argc >= 5)
        randSeed = atoi(argv[5]);
    else
        randSeed = -1;  //if user enters nothing
    
    //nBuffers must be a positive prime integer less than 32
    if (nBuffers < 0) {
        printf("nBuffers must be POSITIVE\n\n");
        exit(-1);
    }//end if
    else if (nBuffers > 32){
        printf("nBuffers must be less than 32\n\n");
        exit(-1);
    }//end else if
    else if (nBuffers % 2 == 0){
        printf("%d is NOT a prime number\n\n", nBuffers);
        exit(-1);
    }//end else if

    //nWorkers must be a positive integer less than nBuffers
    if (nWorkers > nBuffers){
        printf("nWorkers must be less than nBuffers!\n\n");
        exit(-1);
    }//end if
    else if (nWorkers < 0){
        printf("nWorkers must be POSITIVE\n\n");
        exit(-1);
    }//end else if
    
    /**********************/
    /*   SET UP WORKERS   */
    /**********************/

    if (semLock){
        semid = semget(IPC_PRIVATE, nBuffers, IPC_CREAT|0600);
        if (semid < 0){
            perror("semget");
            exit(-1);
        }//end if
        union semun argVal;
        argVal.val = 1;
        int c;
        for (c = 0; c < nBuffers; c++){
            if(semctl(semid, c, SETVAL, argVal) < 0){
                perror("semctl");
                exit(-1);
            }//end if(semctl...)
        }//end for (c = 0...)
    }//end if (semLock...)
    else
        semid = -1;

    //Give each worker a random value
    printf("\n");
    int x;
    for (x = 0; x < nWorkers; x++) {
        randomized = randGen(sleepMin, sleepMax, randSeed);
        nWorkerArr[x] = randomized;
        printf("sleepTime [ %d ] = %f\n", x, randomized);    //sanity test
    }//end for
    printf("\n");
    
    struct threadStruct strand[nWorkers];   //array of M structs

    //fill up these values
    int a;
    for ( a = 0; a < nWorkers; a++){
        strand[a].nBuffers = nBuffers;
        strand[a].workerID = a + 1;
        strand[a].sleepTime = nWorkerArr[a];
        strand[a].semID = semid;
        //strand[a].semID = -1;
        strand[a].mutexID = -1;
        strand[a].buffers = bufArr;
        strand[a].nReadErrors = 0;
    }//end for

    /**********************/
    /*      THREADS       */
    /**********************/

    pthread_t isThread[nWorkers];   //create nWorker threads
    struct threadStruct *structPtr; //struct pointer
    long b;
    int rErrorCounter = 0, wErrorCounter = 0;
    
    for (b = 0; b < nWorkers; b++){
        structPtr = &strand[b]; //assign a pointer to each struct

        //create M threads
        if(pthread_create(&isThread[b], NULL, worker, (void *)structPtr) != 0){
            perror("pthread_create");
            exit(-1);
        }//end if

    }//end for

    for (b = 0; b < nWorkers; b++){
        //join threads
        if(pthread_join(isThread[b], NULL) != 0){
            perror("pthread_join");
            exit(-1);
        }//end if

        //have main increment read error counter
        if (strand[b].nReadErrors != 0){
            rErrorCounter += strand[b].nReadErrors;
        }//end if
    }//end for

    /**********************/
    /*  MAIN PRINTS MSGS  */
    /**********************/

    //examine the contents of each buffer element
    int noErrors = (int)(pow(2, nWorkers) - 1);  //no errors contains (2^nWorkers)-1
    int d;
    printf("\nAll buffers should hold %d\n\n", noErrors);   //sanity test
    for (d = 0; d < nBuffers; d++){
        printf("Buffer %d holds %d\n", d, strand->buffers[d]);  //sanity test
        if (*(strand->buffers) != noErrors){
            wErrorCounter++;
        }//end if
    }//end for
    printf("\n");

    //save the bad bits counter into an array index
    int *badBitsArr; //initialize array with write error counter as its index
    badBitsArr = (int *)malloc(sizeof(int)*wErrorCounter);
    int badBitsIndex = 0;
    int e;
    for (e = 0; e < nBuffers; e++){
        if (*(strand->buffers) != noErrors){
            badBitsArr[badBitsIndex] = e; //save into the array
            badBitsIndex++;   //increment accordingly
            //break out of it once it reaches value of write error counter
            if (badBitsIndex == wErrorCounter){
                break;
            }//end if (badBitsIndex...
        }//end if (*(strand...
        else if(wErrorCounter == 0)
            break;
    }//end for

    //now actually make error reports
    int isBadBits, shiftBadBits;
    int wErrCount = 0;
    int *badBitsArr2; 
    badBitsArr2 = (int *)malloc(sizeof(int)*32);    //calling a 32 bit int array to store some values

    //initialize unused index to -1
    int y;
    for (y = 0; y < 32; y++){
        badBitsArr2[y] = -1;
    }//end for

    //Make error reports for each buffer
    int f, g;
    for (f = 0; f < wErrorCounter; f++){
        g = badBitsArr[f];
        isBadBits = strand->buffers[g];   //put contents of found bad bits into array

        printf("Error in buffer %d. ", g); 
    
        //examine the bad bits
        shiftBadBits = (isBadBits ^ noErrors);
        int z, h = 0;;
        for (z = 0; z < 32; z++){
            if(shiftBadBits & (1 << z)){    //tests which bits are lost to overwriting
                badBitsArr2[h] = z;
                h++;
            }//end if ((shiftBadBits...
        }//end for (z = 0...

        //print out the bad bits
        int i = 0;
        printf("( Bad bits = ");
        while(i < h){
            if (i < (h-1))  //beautify it up
                printf("%d, ", badBitsArr2[i]);
            else
                printf("%d", badBitsArr2[i]);
            wErrCount++;
            i++;
        }
        printf(" )\n");

    }//end for
    printf("\n");

    //main prints the total number of errors
    printf("%d read errors and %d write errors encountered.\n\n", rErrorCounter, wErrCount);

    //detach semaphores
    if(semLock){
        if (semctl(semid, 0, IPC_RMID)){
            perror("semctl");
            exit(-1);
        }//end if (semctl...)
    }//end if(semLock)

    printf("Program exiting...\n\n");
    sleep(1);
    return 0;
    
}//end main
int main(void) {
	
	int semin, semread, semout,semlog;
	union semun arg;
	struct sembuf semopr;
	int shmid_in;/*id of in-share-memory*/
	int shmid_out;/*id of out-share-memory*/
	Shm_in* shm1;/*pointer to in-share-memory*/
	Shm_out* shm2;/*pointer to out-share-memory*/
	pid_t pid;/*to pid tou process*/


	/*******************************************************************/
	/*create the 2 shared-memory segments and attach the 2 segments*/
	if ( ((shmid_in = shmget(1234, sizeof(Shm_in), 0666 | IPC_CREAT)) < 0 ) ||
		((shmid_out = shmget(5678, TXTSIZE+1, 0666 | IPC_CREAT)) < 0) ) {
		perror("shmget");
		exit(1);
	}
	/**/

	if ( ((shm1 = shmat(shmid_in,0,0)) == (char*) -1) ||
		((shm2 = shmat(shmid_out,0,0)) == (char*) -1) ) {
		perror("shmat");
		exit(1);
	}
	/*******************************************************************/

	/* Create semaphores*/
	semin = semget((key_t) 111, 1, IPC_CREAT | 0660);
	semread = semget((key_t) 222, 1, IPC_CREAT | 0660);
	semout = semget((key_t) 333, 1, IPC_CREAT | 0660);
	semlog = semget((key_t) 444, 1, IPC_CREAT | 0660);
	if ( (semin == -1) || (semread == -1) || (semout == -1) || (semlog == -1) )
		exit(-1);
	
	/*initialize semaphores*/
	arg.val=1;
	semctl(semin, 0, SETVAL, arg);//semin se up
	semctl(semout, 0, SETVAL, arg);//semout se up
	
	arg.val=0;
	semctl(semread, 0, SETVAL, arg);//semread se down
	semctl(semlog, 0, SETVAL, arg);//semctl se down
	
	/*fork and check with switch if it is the parent (pid != 0, the program C) or the child (pid=0, the program S)*/
	pid=fork();
	/*if error..*/
	if(pid == -1 ) {
		perror("fork");exit(1);
	}
	/**/
	
	/*...else if, it is the child process-S program*/
	else if (pid == 0) {
		printf("I'm process S - the child\n");
		int counter=0;
		while(counter < MESNUM) {//oso exw akoma aithseis gia na staloun
			/*down(semread)*/
			semopr.sem_num = 0;
			semopr.sem_op = -1;
			semopr.sem_flg = 0;
			semop(semread, &semopr, 1);
			
			//EDW DIAVAZW TA PERIEXOMENA TOU IN//
			
			
			/*up(semin)*/
			semopr.sem_num = 0;
			semopr.sem_op = 1;
			semopr.sem_flg = 0;
			semop(semin, &semopr, 1);
			
			if(fork() != 0 ) { //it is S again..
				continue;
			}
			else {//it is S'...
			
				//PAIRNW TO PID KAI TO ZHTOUMENO KEIMENO - DHLADH TA PERIEXOMENA TOU OUT, KAI TA EPEKSERGAZOMAI//
				
				/*apoktaw prosvash ston semtemp tou antistoixou C' tou opoiou exw to pid*/
				int semtempc = semget((key_t) pid /*TO PID POU MOLIS ELAVA*/, 1, IPC_CREAT | 0660);
				
				/*down(out)*/
				semopr.sem_num = 0;
				semopr.sem_op = -1;
				semopr.sem_flg = 0;
				semop(semout, &semopr, 1);
				
				//EDW GRAFW STO OUT TO PERIEXOMENO TOU TXT//
				
				/*up(semptempc)*/
				semopr.sem_num = 0;
				semopr.sem_op = 1;
				semopr.sem_flg = 0;
				semop(semtempc, &semopr, 1);
				
				//kai twra kleinw...//
				exit(0);
				
			}
		}
	}
	/**/
	
	/*...else, if it is the parent process-C program*/
	else{
		int i;
		/*for(i=0;i<MESNUM;i++) {
			//if(temp == EKTHETIKH...)*/
			if (fork() != 0 ) { //it's the C again ..
				//continue;
				printf("ITS THE C  A G A I N ! ! ! \n");
			}
			
			else { //it is C'..
				/* Create a semaphore semtemp for current process C'*/
    				int semtemp = semget((key_t) getpid(), 1, IPC_CREAT | 0660);
    				if (semtemp == -1) exit(-1);
				/*Initialize it to down*/
				arg.val=0;
				semctl(semtemp, 0, SETVAL, arg);
			
				/*down(semin)*/
				semopr.sem_num = 0;
				semopr.sem_op = -1;
				semopr.sem_flg = 0;
				semop(semin, &semopr, 1);
		
				//GRAFW EDW TO STOIXEIO STHN IN MEMORY//
		
				/*up(semread)*/
				semopr.sem_num = 0;
				semopr.sem_op = 1;
				semopr.sem_flg = 0;
				semop(semread, &semopr, 1);
		
				/*down(semtemp)*/
				semopr.sem_num = 0;
				semopr.sem_op = -1;
				semopr.sem_flg = 0;
				semop(semtemp, &semopr, 1);
			
				//EDW DIAVAZEI TA PERIEXOMENA TOU OUT//
			
				/*up(semout)*/
				semopr.sem_num = 0;
				semopr.sem_op = 1;
				semopr.sem_flg = 0;
				semop(semout, &semopr, 1);
			
				/*down(semlog)*/
				semopr.sem_num = 0;
				semopr.sem_op = -1;
				semopr.sem_flg = 0;
				semop(semtemp, &semopr, 1);
			
				//EDW GRAFEI STO LOG.TXT
			
				/*up(semlog)*/
				semopr.sem_num = 0;
				semopr.sem_op = 1;
				semopr.sem_flg = 0;
				semop(semlog, &semopr, 1);
			}
		/*}*/

	}
	/**/


	
	/*delete semaphores*/
	semctl(semin, 0, IPC_RMID, 0);
	semctl(semout, 0, IPC_RMID, 0);
	semctl(semread, 0, IPC_RMID, 0);
	semctl(semlog, 0, IPC_RMID, 0);

	
	
	/*deattach memory segments*/
	if( (shmdt(shm1) == -1 ) || (shmdt(shm2) == -1) ) {
		perror("shmdt");
		exit(1);
	} 
	/**/
	
	/*destroy memory segments*/
	if ( (shmctl(shmid_in,IPC_RMID,0) == -1) || (shmctl(shmid_out,IPC_RMID,0) == -1) ) {
		perror("shmctl");
		exit(1);
	}
	/**/
	
	return 0;
}
Пример #21
0
int main(int argc,char *argv[]){
	signal(SIGINT,handle);
	//先实现共享内存
	if(4!=argc){
		printf("error args\n");
		return -1;
	}
	key_t key;
	key=ftok(argv[1],1);
	if(-1==key){
		perror("ftok");
		return -1;
	}
	int shmid;
	shmid=shmget(key,1<<10,IPC_CREAT|0600);
	if(-1==shmid){
		perror("shmget");
		return -1;
	}
	pchat c;
	c=(pchat)shmat(shmid,NULL,0);
	if((pchat)-1==c){
		perror("shmat");
		return -1;
	}
	//独占的共享内存因此需要设置信号量
	int semid;
	semid=semget((key_t)1002,1,IPC_CREAT|0600);
	semctl(semid,0,SETVAL,1);
	struct sembuf p,v;//num,op,flg
	p.sem_num=0;
	p.sem_op=-1;
	p.sem_flg=SEM_UNDO;//一般都用这个
	v.sem_num=0;
	v.sem_op=1;
	v.sem_flg=SEM_UNDO;
	//管道通信连接管道
	int fdpr,fdpw;
	fdpw=open(argv[2],O_WRONLY);
	if(-1==fdpw){
		perror("openw");
		return -1;
	}
	fdpr=open(argv[3],O_RDONLY);
	if(-1==fdpr){
		perror("openr");
		return -1;
	}
	//等待标准输入和可读
	//int select(int maxfd, fd_set *readset,fd_set *writeset,
	//fd_set *exceptionset, const struct timeval * timeout);
	fd_set s;
	int ret;
	char buf[L];
	while(1){
		FD_ZERO(&s);
		FD_SET(0,&s);
		FD_SET(fdpr,&s);
		ret=select(fdpr+1,&s,NULL,NULL,NULL);
		if(-1==ret){
			perror("select");
			return -1;
		}
		//龙哥说考虑并发,最好是在这里完成加工,一起写入到共享内存,在上层
		//只做打印界面
		if(FD_ISSET(0,&s)){
		//标准输入,应该写入管道,并写入共享内存中,标记为自己的信息1
			memset(buf,0,sizeof(buf));
			read(0,buf,sizeof(buf));
			write(fdpw,buf,strlen(buf)-1);
			semop(semid,&p,1);
			if(0==c->isnew){
				strncpy(c->buf,buf,strlen(buf)-1);
				c->isnew=1;
			}
			semop(semid,&v,1);
		}
		if(FD_ISSET(fdpr,&s)){
		//管道可读,应该写到共享内存中,标记为别人的信息2
			memset(buf,0,sizeof(buf));
			ret=read(fdpr,buf,sizeof(buf));
			if(ret<=0){
				perror("read");
				return -1;
			}
			semop(semid,&p,1);
			if(0==c->isnew){
				strncpy(c->buf,buf,strlen(buf));
				c->isnew=2;
			}
			semop(semid,&v,1);
		}
	}
}
Пример #22
0
void init_shm(void)
{
    int i;

	/* Create, attach and mark for death the big buffer */
    shmid = shmget(IPC_PRIVATE, BIGBUFFSIZE,
	IPC_EXCL | IPC_CREAT | 0600);
    if (shmid == -1)
	ErrDie("shmget");
    bigbuff = shmat(shmid, IPC_RMID, SHM_RND);
    if (bigbuff == (char*)-1)
    {
	perror("shmat");
	if(shmctl(shmid, IPC_RMID, NULL))
		perror("shmctl");
	exit(-1);
    }
    if(shmctl(shmid, IPC_RMID, NULL))
	ErrDie("shmctl");

    /* Create an array of pointers. Point them at equally spaced
    ** chunks in the main buffer, to give lots of smaller buffers
    */
    numbuffs = BIGBUFFSIZE/abuf_size;
    buffarr = (char**)malloc(numbuffs*sizeof(char*));
    for (i=0; i<numbuffs; i++)
	buffarr[i] = bigbuff + i * abuf_size;

    /* Create a small amount of shared memory to hold the info
    ** for each buffer.
    */
    shmid2 = shmget(IPC_PRIVATE, numbuffs*sizeof(blockinf_t),
	IPC_EXCL | IPC_CREAT | 0600);
    if (shmid == -1)
	ErrDie("shmget");
    buffinf = (blockinf_t*)shmat(shmid2, IPC_RMID, SHM_RND);
    if (buffinf == (blockinf_t*)((char*)-1))
    {
	perror("shmat");
	if(shmctl(shmid2, IPC_RMID, NULL))
		perror("shmctl");
	exit(-1);
    }
    if(shmctl(shmid2, IPC_RMID, NULL))
	ErrDie("shmctl");
     
    /* Set up the appropriate number of semaphore blocks */
    numsemblks = numbuffs/SEMMSL;
    if((numsemblks * SEMMSL) < numbuffs)
	numsemblks++;
    /* Malloc arrays of semaphore ids (ints) for the semaphores */
    if ((disksemid = (int*)malloc(sizeof(int)*numsemblks)) == NULL)
	ErrDie("malloc");
    if ((sndsemid = (int*)malloc(sizeof(int)*numsemblks)) == NULL)
	ErrDie("malloc");
    /* Create the semaphores */
    for (i=0;i<numsemblks;i++)
    {
	if ((disksemid[i] = semget(IPC_PRIVATE, SEMMSL,
	    IPC_EXCL | IPC_CREAT | 0600)) == -1)
	    ErrDie("semget");
	if ((sndsemid[i] = semget(IPC_PRIVATE, SEMMSL,
	    IPC_EXCL | IPC_CREAT | 0600)) == -1)
	    ErrDie("semget");
    }
    /* Catch some signals, so we clean up semaphores */
    signal(SIGINT, sighandler);
}
Пример #23
0
/*
 * Initialize the Interprocess Communication system and its associated shared
 * memory structure. It first creates a temporary file using the mkstemp()
 * function. It than sets the file large enough to hold the filebench_shm and an
 * additional megabyte.  (Additional megabyte is required to make sure that all
 * sizeof(filebench_shm) bytes plus page alignment bytes will fit in the file.)
 * The file is then memory mapped. Once the shared memory region is created,
 * ipc_init initializes various locks, pointers, and variables in the shared
 * memory. It also uses ftok() to get a shared memory semaphore key for later
 * use in allocating shared semaphores.
 */
void ipc_init(char *fsplug)
{
	int shmfd;
	char tmpbuf[MB] = {0};
	key_t key;
#ifdef HAVE_SEM_RMID
	int sys_semid;
#endif
	char *shmdir;

	shmdir = getenv("FB_SHM_DIR");
	if (shmdir == NULL)
	    shmdir = "/tmp";

	if (asprintf(&shmpath, "%s/filebench-shm-XXXXXX", shmdir) < 0) {
		filebench_log(LOG_FATAL, "Could not name shared memory file");
		exit(1);
	}

	shmfd = mkstemp(shmpath);
	if (shmfd  < 0) {
		filebench_log(LOG_FATAL, "Could not create shared memory "
			      "file %s: %s", shmpath, strerror(errno));
		exit(1);
	}

	(void)lseek(shmfd, sizeof(filebench_shm_t), SEEK_SET);
	if (write(shmfd, tmpbuf, MB) != MB) {
		filebench_log(LOG_FATAL,
		    "Could not write to the shared memory "
		    "file: %s", strerror(errno));
		exit(1);
	}

	if ((filebench_shm = (filebench_shm_t *)mmap(NULL,
	    sizeof(filebench_shm_t), PROT_READ | PROT_WRITE,
	    MAP_SHARED, shmfd, 0)) == MAP_FAILED) {
		filebench_log(LOG_FATAL, "Could not mmap the shared "
		"memory file: %s", strerror(errno));
		exit(1);
	}

	(void) memset(filebench_shm, 0,
		 (char *)&filebench_shm->shm_marker - (char *)filebench_shm);

	/*
	 * Pass the name of the target filesystem, if not the local driver
	 */
	if (fsplug)
		fb_strlcpy(filebench_shm->shm_filesys_path,fsplug,
			   sizeof(filebench_shm->shm_filesys_path));

	/*
	 * First, initialize all the structures needed for the filebench_log()
	 * function to work correctly with the log levels other than LOG_FATAL
	 */
	filebench_shm->shm_epoch = gethrtime();
	filebench_shm->shm_debug_level = LOG_INFO;

	/* Setup mutexes for object lists */
	ipc_mutexattr_init(IPC_MUTEX_NORMAL);
	ipc_mutexattr_init(IPC_MUTEX_PRIORITY);
	ipc_mutexattr_init(IPC_MUTEX_ROBUST);
	ipc_mutexattr_init(IPC_MUTEX_PRI_ROB);

	(void) pthread_mutex_init(&filebench_shm->shm_msg_lock,
	    ipc_mutexattr(IPC_MUTEX_NORMAL));

	filebench_log(LOG_INFO, "Allocated %lldMB of shared memory",
			(sizeof(filebench_shm_t) + MB) / MB);

	filebench_shm->shm_rmode = FILEBENCH_MODE_TIMEOUT;
	filebench_shm->shm_string_ptr = &filebench_shm->shm_strings[0];
	filebench_shm->shm_ptr = (char *)filebench_shm->shm_addr;
	filebench_shm->shm_path_ptr = &filebench_shm->shm_filesetpaths[0];

	(void) pthread_mutex_init(&filebench_shm->shm_fileset_lock,
	    ipc_mutexattr(IPC_MUTEX_NORMAL));
	(void) pthread_mutex_init(&filebench_shm->shm_procflow_lock,
	    ipc_mutexattr(IPC_MUTEX_NORMAL));
	(void) pthread_mutex_init(&filebench_shm->shm_procs_running_lock,
	    ipc_mutexattr(IPC_MUTEX_NORMAL));
	(void) pthread_mutex_init(&filebench_shm->shm_threadflow_lock,
	    ipc_mutexattr(IPC_MUTEX_NORMAL));
	(void) pthread_mutex_init(&filebench_shm->shm_flowop_lock,
	    ipc_mutexattr(IPC_MUTEX_NORMAL));
	(void) pthread_mutex_init(&filebench_shm->shm_eventgen_lock,
	    ipc_mutexattr(IPC_MUTEX_PRI_ROB));
	(void) pthread_mutex_init(&filebench_shm->shm_malloc_lock,
	    ipc_mutexattr(IPC_MUTEX_NORMAL));
	(void) pthread_mutex_init(&filebench_shm->shm_ism_lock,
	    ipc_mutexattr(IPC_MUTEX_NORMAL));
	(void) ipc_mutex_lock(&filebench_shm->shm_ism_lock);
	(void) pthread_cond_init(&filebench_shm->shm_eventgen_cv,
	    ipc_condattr());
	(void) pthread_rwlock_init(&filebench_shm->shm_flowop_find_lock,
	    ipc_rwlockattr());
	(void) pthread_rwlock_init(&filebench_shm->shm_run_lock,
	    ipc_rwlockattr());

	/* Create semaphore */
	if ((key = ftok(shmpath, 1)) < 0) {
		filebench_log(LOG_ERROR, "cannot create sem: %s",
		    strerror(errno));
		exit(1);
	}

#ifdef HAVE_SEM_RMID
	if ((sys_semid = semget(key, 0, 0)) != -1)
		(void) semctl(sys_semid, 0, IPC_RMID);
#endif

	filebench_shm->shm_semkey = key;
	filebench_shm->shm_sys_semid = -1;
	filebench_shm->shm_dump_fd = -1;
	filebench_shm->shm_eventgen_hz = 0;
	filebench_shm->shm_id = -1;
}
int create_sem(key_t key, const int sem_size, const char *txt, const char *etxt, int flags) {
  int semaphore_id = semget(key, sem_size, flags | PERM);
  handle_error(semaphore_id, etxt, PROCESS_EXIT);
  return semaphore_id;
}
Пример #25
0
int OptLogInit()
{
    int ret;
    int cfglen;
    int i;
    int j;
    setlinebuf(stdout);
    EngModePrintOn=0;
    ST_OptLogCfgData sval;
    ST_OptLogCfgInfo *cfginf = NULL;
    bzero(&sval,sizeof(sval));
    
    Debug_print("%s\n",CONFIG_FILE);

	if (gendata.initlized)
	{
		Debug_print("The operation log has been initlized ,can not init again\n");
		return 0;
	}
    ret = ReadCfg(CONFIG_FILE,&cfginf,&cfglen);
    if (ret < 0)
    {
        printf("read configuration file failed, use default set\n");
        sval.curlevel = 3;
        sval.enflags |= PrtAllComp;
        if (!getcwd(sval.rcdpath,PATHLEN)) 
        {
            perror("get current directory failed");
            return -1;
        }
    }
    for (i=0;i<cfglen;i++)
    {
        Debug_print("key:%s\t val:%s\n",cfginf[i].key,cfginf[i].val); 
        if (!strcmp(cfginf[i].key,"prtlevel")&&cfginf[i].val[0]!='0')
        {
	    	sval.enflags |= EnLevel; 
            continue;
        }
        if (!strcmp(cfginf[i].key,"prtfilename")&&cfginf[i].val[0]!='0')
        {
	    	sval.enflags|= EnFName; 
            continue;
        }
        if (!strcmp(cfginf[i].key,"prtfuncname")&&cfginf[i].val[0]!='0')
        {
	    	sval.enflags|= EnFcName; 
            continue;
        }
        if (!strcmp(cfginf[i].key,"prtlinenum")&&cfginf[i].val[0]!='0')
        {
	    	sval.enflags|= EnLine; 
            continue;
        }
        if (!strcmp(cfginf[i].key,"prttime")&&cfginf[i].val[0]!='0')
        {
	    	sval.enflags|= EnTime; 
            continue;
        }
        if (!strcmp(cfginf[i].key,"prtinfile")&&cfginf[i].val[0]!='0')
        {
	    	sval.enflags|= EnFRcd; 
            continue;
        }
        if (!strcmp(cfginf[i].key,"recordpath")&&cfginf[i].val[0]!=0)
        {
            int slen;
            slen = strlen(cfginf[i].val);
            if (cfginf[i].val[slen-1] == '/')
            {
                cfginf[i].val[slen-1] = 0;
            }
	    	strncpy(sval.rcdpath,cfginf[i].val,PATHLEN);
            continue;
        }
        if (!strcmp(cfginf[i].key,"level")&&cfginf[i].val[0]!=0)
        {
            sval.curlevel = atoi(cfginf[i].val);
            continue;
        }
        if (!strcmp(cfginf[i].key,"componentlist")&&cfginf[i].val[0]!=0)
        {
            if (GetComps(cfginf[i].val,&sval) < 0)
            {
                Debug_print("get components list failed\n");
            }
            else
            {
                for (j=0;j<sval.compnum;j++)
                Debug_print("component name:%s\n",sval.comp[j]);
            }
            continue;
        }
         
    }
    if (cfginf)
    {
        free(cfginf);
    }
    Debug_print("enflag:%x\tpath:%s\n",sval.enflags,sval.rcdpath);
    //create shared memory and init semaphore
    gendata.shmid = shmget(IPC_KEY,sizeof(ST_OptLogCfgData),0666);
    if (gendata.shmid == -1)
    {
        Debug_print("shared memory does not exist,need create\n");
        gendata.shmid = shmget(IPC_KEY,sizeof(ST_OptLogCfgData),0666|IPC_CREAT);
        if (gendata.shmid < 0)
        {
            perror("create shared memory failed");
            return -1;
        }
        Debug_print("create shared memory success\n");
    } 
    else
    {
        sval.enflags |= SMemExist;
    }
    Debug_print("get shared memory success\n");
    gendata.cfg = (ST_OptLogCfgData *)shmat(gendata.shmid,NULL,0);
    if (gendata.cfg == (void *)-1)
    {
        perror("get shared memory address failed");
        shmctl(gendata.shmid,IPC_RMID,NULL);
        gendata.cfg = NULL;
        return -1;
    }
    //bzero(gendata.cfg,4096*65);

    Debug_print("get shared memory address success\n");

    gendata.semid = semget(SEM_KEY,0,0666);
    if (gendata.semid < 0)
    {
        Debug_print("semaphore is not created, need create\n");
        gendata.semid = semget(SEM_KEY,1,0666|IPC_CREAT);
        if (gendata.semid < 0)
        {
            perror("create semaphore failed");
            return -1;
        }
        Debug_print("create semaphore success\n");
        if (init_sem(gendata.semid,1) < 0)
        {
            printf("init semaphore failed\n");
            del_sem(gendata.semid);
            return -1;
        }
        Debug_print("init semaphore success\n");
    }
    Debug_print("get semaphore success\n");
    if(pthread_mutex_init(&gendata.filemutex,NULL) != 0)
    {
        perror("create file mutex failed");
        return -1;
    }
    if(pthread_mutex_init(&gendata.pathmutex,NULL) != 0)
    {
        perror("create path mutex failed");
        return -1;
    }
    #ifdef READ_CFG
    if (1) 
    #else
    if (!(sval.enflags&SMemExist))
    #endif
    {
        Debug_print("shared memory does not exists need to set value to memory\n");
        Debug_print("curlevel:%d\trcdpath:%s\tcomnum:%d\tenflags:%x\n",sval.curlevel,\
        sval.rcdpath,sval.compnum,sval.enflags);
        OptLogSet(&sval);
    }
	gendata.initlized = 1;
    return 0;
}
Пример #26
0
int
main(int argc, char *argv[])
{
	struct sigaction sa;
	union semun sun;
	struct semid_ds s_ds;
	sigset_t sigmask;
	int i;

	if (argc != 2)
		usage();

	/*
	 * Install a SIGSYS handler so that we can exit gracefully if
	 * System V Semaphore support isn't in the kernel.
	 */
	sa.sa_handler = sigsys_handler;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	if (sigaction(SIGSYS, &sa, NULL) == -1)
		err(1, "sigaction SIGSYS");

	/*
	 * Install and SIGCHLD handler to deal with all possible exit
	 * conditions of the receiver.
	 */
	sa.sa_handler = sigchld_handler;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	if (sigaction(SIGCHLD, &sa, NULL) == -1)
		err(1, "sigaction SIGCHLD");

	semkey = ftok(argv[1], 4160);

	/*
	 * Initialize child_pid to ourselves to that the cleanup function
	 * works before we create the receiver.
	 */
	child_pid = getpid();

	/*
	 * Make sure that when the sender exits, the message queue is
	 * removed.
	 */
	if (atexit(cleanup) == -1)
		err(1, "atexit");

	if ((sender_semid = semget(semkey, 1, IPC_CREAT | 0640)) == -1)
		err(1, "semget");

	
	sun.buf = &s_ds;
	if (semctl(sender_semid, 0, IPC_STAT, sun) == -1)
		err(1, "semctl IPC_STAT");

	print_semid_ds(&s_ds, 0640);

	s_ds.sem_perm.mode = (s_ds.sem_perm.mode & ~0777) | 0600;

	sun.buf = &s_ds;
	if (semctl(sender_semid, 0, IPC_SET, sun) == -1)
		err(1, "semctl IPC_SET");

	memset(&s_ds, 0, sizeof(s_ds));

	sun.buf = &s_ds;
	if (semctl(sender_semid, 0, IPC_STAT, sun) == -1)
		err(1, "semctl IPC_STAT");

	if ((s_ds.sem_perm.mode & 0777) != 0600)
		err(1, "IPC_SET of mode didn't hold");

	print_semid_ds(&s_ds, 0600);

	for (child_count = 0; child_count < 5; child_count++) {
		switch ((child_pid = fork())) {
		case -1:
			err(1, "fork");
			/* NOTREACHED */

		case 0:
			waiter();
			break;

		default:
			break;
		}
	}

	/*
	 * Wait for all of the waiters to be attempting to acquire the
	 * semaphore.
	 */
	for (;;) {
		i = semctl(sender_semid, 0, GETNCNT);
		if (i == -1)
			err(1, "semctl GETNCNT");
		if (i == 5)
			break;
	}

	/*
	 * Now set the thundering herd in motion by initializing the
	 * semaphore to the value 1.
	 */
	sun.val = 1;
	if (semctl(sender_semid, 0, SETVAL, sun) == -1)
		err(1, "sender: semctl SETVAL to 1");

	/*
	 * Suspend forever; when we get SIGCHLD, the handler will exit.
	 */
	sigemptyset(&sigmask);
	for (;;) {
		(void) sigsuspend(&sigmask);
		if (signal_was_sigchld)
			signal_was_sigchld = 0;
		else
			break;
	}

	/*
	 * ...and any other signal is an unexpected error.
	 */
	errx(1, "sender: received unexpected signal");
}
Пример #27
0
TVerdict CSetjmpTest::setjmpTest()
	{
	SetTestStepResult(EFail);
	int             autoval;
	register int    regival;
	volatile int    volaval;
	static int      statval;
	int             result;

	// for each type of storage' variable, set initialize value
	globval = KGLOBVALINIT; 
	autoval = KAUTOVALINIT; 
	regival = KREGVALINIT; 
	volaval = KVOLAVALINIT; 
	statval = KSTATVALINIT; 
		
	GetBoolFromConfig(ConfigSection(), KCreateThreadFormat, iCreateThread);
	GetBoolFromConfig(ConfigSection(), KCreateProcessFormat, iCreateProcess);
	GetBoolFromConfig(ConfigSection(), KCallSetjmpTwiceFormat, iCallSetjmpTwice);
	GetIntFromConfig(ConfigSection(), KLongJmpBufIndexFormat, iLongJmpBufIndex);
	GetStringFromConfig(ConfigSection(), KWorkerProcessName, iWorkerProcessName);
	
	// first long jump return entry
	if( (result = setjmp(iJmpBuffer[0]))!= 0)
	   	{  
    	if(result == KLONGJUMPRETURNVAL)
        	 {
           	 if(CompareToExpectedValue( globval,autoval, regival, volaval, statval))
        	     {
        	     return TestStepResult();
        	     }
        	 else
        		 {
        		 SetTestStepResult(EPass);
        		 return TestStepResult();
        		 }
        	 }
         else
        	 {
        	 return TestStepResult();
        	 }
    	}
 /*
  * Change variables after setjmp, but before longjmp.
  */
	globval = KGLOBVALFIRST; 
	autoval = KAUTOVALFIRST; 
	regival = KREGVALFIRST; 
	volaval = KVOLAVOLFIRST; 
	statval = KSTATVALFIRST; 
	if(iCallSetjmpTwice)
    	{
    	result = setjmp(iJmpBuffer[1]);
    	if(result != 0) 
    		{
    	    if(result == KLONGJUMPRETURNVAL)
    	    	{
    	       	if(CompareToExpectedValue( globval,autoval, regival, volaval, statval))
    	    		{
    	    		return TestStepResult();
    	    		}
     	  	    else
     	  	    	{
     	  	    	SetTestStepResult(EPass);
     	  	    	return TestStepResult();
     	  	    	}
    	    	}
    	    else
    	    	{
    	    	return TestStepResult();
    	    	}
    		}
	    //second long jump return entry
	 	globval = KGLOBVALSECOND; 
	 	autoval = KAUTOVALSECOND; 
	 	regival = KREGVALSECOND; 
	 	volaval = KVOLAVALSECOND; 
	 	statval = KSTATVALSECOND;
	  	}
    
    
    // create a thread and run it in between
	if(iCreateThread)
		{
	    pthread_t testthread;
		pthread_create(&testthread, NULL, (thread_begin_routine) &threadfunction, NULL);	
		pthread_join(testthread, NULL);
		}
	else if(iCreateProcess)
		{
		int semid; 
		key_t key = MYSEMAPHOREKEY; 
		int semflg = IPC_CREAT | GETSETOPTION; 
		int nsems = 1; 

		// set up semaphore 
		semid = semget(key, nsems, semflg);
		if (semid == -1) 
			{
			ERR_PRINTF1(_L("Semaphore initialized failed \n"));
			return TestStepResult();
			} 
		else 
			{
			_LIT(Ksem,"Semaphore initialized success with id: %d \n");
			INFO_PRINTF2(Ksem, semid);
			}

		// create a new file for testing
		char testfilename[L_tmpnam];
		int testfileD = open(tmpnam(testfilename), O_CREAT | O_RDWR);
		if(-1 == testfileD)
			{
			ERR_PRINTF1(_L("Test file can not be opened."));
			return TestStepResult();
			}
		// Create child process using popen(). Child process writes to the Parent therefore "r" 
				
		 char* childprocessbinaryname = (char*) malloc(sizeof(char) * COMMANDLINELEN);
		 char* firstcommandline = (char*) malloc(sizeof(char) * COMMANDLINELEN);
				
		// check buffer, if can not be allocated, then leave
		if(NULL == childprocessbinaryname || NULL == firstcommandline)
			{
			free(childprocessbinaryname);
			free(firstcommandline);			
			User::Leave(KErrGeneral);
			}
		CopyTDescToString(iWorkerProcessName, childprocessbinaryname);
		sprintf(firstcommandline, "%s %d %s %d %d", 
						childprocessbinaryname,
						semid,
						testfilename,
						COMMANDLINELEN,
						BYTEVALUE);	
		FILE* cpFirstAppender = popen(firstcommandline,"r");
		if(cpFirstAppender == NULL)
			{
			ERR_PRINTF1(_L("Sub process created failed."));
			return TestStepResult();
			}
		ssize_t sz = fread(firstcommandline,COMMANDLINELEN,1,cpFirstAppender);
		int ret = pclose(cpFirstAppender);
		free(childprocessbinaryname);
		free(firstcommandline);
		}
	longjmp(iJmpBuffer[iLongJmpBufIndex], KLONGJUMPRETURNVAL);
	SetTestStepResult(EPass);
	return TestStepResult();
	}
Пример #28
0
int main(int argc, char const *argv[])
{
	int n;						// number of lions
	int k;						// number of times each lion is going to eat
	pid_t *pid;
	int status;

	int i,j;					// iterating variables
	int curr_pit;				// stores the current pit from which the lion is going to eat

	int check;					// stores the pit that will be available;

	// read the number of lions form arguments
	if(argc < 3)
	{
		perror("Didn't provide the number of lions");
		exit(0);
	}
	// Read the number of lions
	n = atoi(argv[1]);
	// Read the number of times each lion is going to eat
	k = atoi(argv[2]);


	pid = (pid_t*)malloc(n*sizeof(pid_t));
	// Wait for the start signal from the Ranger

	// Create Semaphores
	sem_mut 	= semget(MUTEX, 1, IPC_CREAT|0666);
	sem_lion 	= semget(LION, N_PITS + 1, IPC_CREAT|0666);
	sem_jackal 	= semget(JACKAL, N_PITS + 1, IPC_CREAT|0666);
	sem_ranger 	= semget(RANGER, N_PITS + 1, IPC_CREAT|0666);
	sem_pit 	= semget(PIT, N_PITS + 1, IPC_CREAT|0666);
	sem_mem		= semget(NEXT_PIT, 1, IPC_CREAT|0666);
	sem_lion_init = semget(INIT_LION, 1, IPC_CREAT|0666);
	semctl(sem_lion_init,0,SETVAL,0);
	down(sem_lion_init,0);
	printf("Lion Started %d %d\n",n,k);

	// fork n lions
	for(i = 0; i < n; i++)
	{
		pid[i] = fork();
		if(pid[i] == 0)
		{
			srand(time(NULL));
			// forked process
			// actual lion code
			id = i;
			// chosen a random pit
			curr_pit = rand()%N_PITS + 1;
			for(j = 0; j < k; j++)
			{

				check = check_availability(curr_pit);
				if(check == -1)
				{
					// no pit available
					curr_pit = (curr_pit - 1 + N_PITS - 1)%N_PITS + 1;
					printf("%s %d in wait queue of meat-pit %d\n",SELF,id,curr_pit);
					// block in the waiting queue
					down(sem_self,0);
					curr_pit = semctl(sem_mem,0,GETVAL,0);
					j--;
					continue;
				}
				//Current consumer will eat from meat-pit number 'check'
				curr_pit = check;

				// Take control
				printf("Before::Number of %s in meat-pit %d = %d\t\t\t%s %d\n",SELF,curr_pit,semctl(sem_self,curr_pit,GETVAL,0),SELF,id);
				up(sem_self,curr_pit);
				printf("After::Number of %s in meat-pit %d = %d\t\t\t%s %d\n",SELF,curr_pit,semctl(sem_self,curr_pit,GETVAL,0),SELF,id);
				printf("%s %d in control of meat-pit %d\n\n\n",SELF,id,curr_pit);
				// Consume
				down(sem_pit,curr_pit);
				printf("\t\t\t\t\t Meat in Pits %d %d %d\n",semctl(sem_pit, 1, GETVAL, 0),semctl(sem_pit, 2, GETVAL, 0),semctl(sem_pit, 3, GETVAL, 0));
				sleep(2);
				// Check if last consumer to leave the pit

				printf("Number of %s in meat-pit %d = %d\t\t\t%s %d\n",SELF,curr_pit,semctl(sem_self,curr_pit,GETVAL,0),SELF,id);
				if(semctl(sem_self,curr_pit,GETVAL,0) > 1)// || semctl(sem_pit,curr_pit,GETVAL,0) == 0)
				{
					// do not send signal and continue
					down(sem_self,curr_pit);
					continue;
				}
				printf("Down karega %s %d\n",SELF,id);
				down(sem_self,curr_pit);

//				down(sem_mut,0);

				printf("%s %d left meat-pit %d\n",SELF,id,curr_pit);
				// send signals
				// set shared memory to current pit
				semctl(sem_mem,0,SETVAL,curr_pit);
				// wake up ranger and rival
				if(semctl(sem_ranger,0,GETVAL,0) == 0)				// wake up ranger only when sleeping
				up(sem_ranger,0);
				if(semctl(sem_rival, 0, GETNCNT, 0) == 0)
					printf("Koi uthane ko nahi hai %s %d\n",SELF,id);			
				printf("\t\t\tNumber of Jackals waiting %d\n",semctl(sem_jackal, 0, GETNCNT, 0));
				printf("\t\t\tNumber of Lions waiting %d\n",semctl(sem_lion, 0, GETNCNT, 0));
				upn(sem_rival,0,semctl(sem_rival, 0, GETNCNT, 0));
				printf("%s %d giving signal to wait queue of all meat-pit\n",SELF,id);
				
				curr_pit = rand()%N_PITS + 1;
				
//				up(sem_mut,0);
			}
			exit(0);
		}
		else if(pid[i] < 0)
		{
			perror("Fork error!!");
			exit(0);
		}
	}
	for(i = 0; i < n; i++)
		waitpid(pid[i],&status,0);
	free(pid);
	return 0;
}
Пример #29
0
int main()
{
    int i;
    int prio_inheritance=0;

    /*
    int shm_id=0;
    char *shm, *s;
     FILE *f = fopen("shared_mem_info.txt","r");
        if (f == NULL)
        {
                printf("Error in opening file!!! \n");
                exit(1);
        }
    fscanf(f,"%d",&shm_id);
    fclose(f);
    printf("shared memory id = %d \n",shm_id);


    }
    */
    /************************************* Process 1 (High Priority) *********************************/

    key_t key;
    int shm_id;
    char *shm, *s;
    char c;

    key = 5788; // name the shared memory
    shm_id= shmget(key,100, IPC_CREAT | 0666); // make a shared memory of 27 bytes
    if(shm_id < 0)
    {
        perror("shmget");
        exit(1);
    }
    // Now attach the shared memory to our data space
    if((shm = shmat(shm_id,NULL,0)) == (char *) -1)
    {
        perror("shmat");
        exit(1);
    }

    s = shm;  // Now we will write in the memory

    FILE *f = fopen("shared_mem_info.txt","w");
    if (f == NULL)
    {
        printf("Error in opening file!!! \n");
        exit(1);
    }
    fprintf(f,"%d\n",shm_id);
    fclose(f);

    sem_id = semget(key,1,0666 | IPC_CREAT);
    if(!set_semvalue())
    {
        fprintf(stderr,"Failed to initiaalize the semaphore \n");
        exit(EXIT_FAILURE);
    }

    // It is the parent process. I have schedule it as high priority process.
    int PID_H = getpid();
    int PR_H = getpriority(PRIO_PROCESS,PID_H);
    printf("The Priority of High Process %d = %d\n", PID_H,PR_H);
    setpriority(PRIO_PROCESS,PID_H,PRIO_H);
    printf("The Priority of High Process %d changes = %d\n", PID_H,PRIO_H);

    usleep(200);
    printf("High Prio task is now try to access the semaphore...\n");

    union semun sem_union;
    who_locked = semctl(sem_id,0,GETPID,sem_union);
//	if(who_locked != PID_H)
//	{
    if(who_locked > 0)
    {
        printf("The PID = %d has locked the Semaphore. . . \n",who_locked);
        /*setpriority(PRIO_PROCESS,who_locked,PRIO_H);
        prio_inheritance = 1;
        printf("The PID = %d has inherited priority of High that is %d...\n",who_locked,PRIO_H);
        sched_yield();*/
    }
//	}


    sem_lock();
    printf("High process has acquired the lock\n");
    printf("Address = %d\n",shm);
    for(c='a'; c<='z'; c++)
    {
        *s++ = c;
    }
    *s=NULL;
    printf("write succesfull...\n");

    while(*shm != '*')
    {
        sleep(1);
    }
    for(i=0; i<40; i++)
        printf("High Prio task is running...\n");
    sem_unlock();
    printf("High process has unlock the semaphore... \n");
    return 0;

}
Пример #30
0
SEMAPHORE::SEMAPHORE(int size) {

	this->size = size;
	semid = semget(IPC_PRIVATE, size, PERMS);
	init();
	}