Example #1
0
/************************************************************
 * function:  destroy or close the shared memory.
 * iscreated: 1, to destroy the shm; 0, only to close the shm.
 * return:    0, correct; others, error number.
 ***********************************************************/
int shmmq_close(int isdestroyed)
{
	int ret = 0;

	if (g_s_pbase) {
		if (-1 == shmdt(g_s_pbase)) {
			ret = ERROR_SHMDT;
		}
		g_s_pbase = NULL;
	}

	if (!isdestroyed) return ret;

	if (g_s_shmid >= 0) {
		if (shmctl(g_s_shmid, IPC_RMID, 0) == -1) {
			ret = ERROR_SHMCTL;
        	}
		g_s_shmid = -1;
	}

	if (g_s_semid >= 0) {
		if (-1 == del_semvalue(g_s_semid)) {
			ret = ERROR_DEL_SEMVALUE;
		}
		g_s_semid = -1;
	}

	return ret;
}
Example #2
0
int main(int argc,char **argv)
{
	int i ;
	int pause_time;
	char op_char = 'O';
	srand((unsigned int)getpid());

    //create semaphore
	sem_id = semget((key_t)1234,1,0666|IPC_CREAT);

	if (argc >1)
	{
		//set sempvalue 初始化信号量
		if (!set_semvalue())
		{
			fprintf(stderr,"Failed to initialize semaphore");
			exit(EXIT_FAILURE);
		}
		op_char = 'X';
		sleep(2);
	}

	for (i = 0; i < 10; ++i)
	{
		//设置信号量 等待进入
		if (!semaphore_p())
		{
			exit(EXIT_FAILURE);
		}
		printf("%c",op_char);
		fflush(stdout);
		pause_time = rand() % 3;
		sleep(pause_time);
		printf("%c",op_char);
		fflush(stdout);

		//退出临界区,信号量设置为可用
		if (!semaphore_v())
		{
			exit(EXIT_FAILURE);
		}
		pause_time = rand() % 3;
		sleep(pause_time);
	}
	printf("\n%d - finished \n",getpid());
	
	if (argc>1)
	{
		sleep(10);
		//删除信号量
		del_semvalue();
	}
	exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[])
{
     char message = 'X';
     int i = 0;
 
    /* 创建信号量 */
    sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT);
 
    if(argc > 1)
    {
        /* 程序第一次被调用,初始化信号量 */
        if(!set_semvalue())
        {
            fprintf(stderr, "Failed to initialize semaphore\n");
            exit(EXIT_FAILURE);
        }
        /* 设置要输出到屏幕中的信息,即其参数的第一个字符 */
        message = argv[1][0];
        sleep(2);
    }

    for(i = 0; i < 10; ++i)
    {
         /* 进入临界区 */
        if(!semaphore_p())
        {
            exit(EXIT_FAILURE);
        }
        /* 向屏幕中输出数据 */
        printf("%c", message);
        /* 清理缓冲区,然后休眠随机时间 */
        fflush(stdout);
        sleep(rand() % 3);
        /* 离开临界区前再一次向屏幕输出数据 */
        printf("%c", message);
        fflush(stdout);
        /* 离开临界区,休眠随机时间后继续循环 */
        if(!semaphore_v())
        {
            exit(EXIT_FAILURE);
        }
        sleep(rand() % 2);
    }
    sleep(10);
    printf("\n%d - finished\n", getpid());
 
    if(argc > 1)
    {
        /* 如果程序是第一次被调用,则在退出前删除信号量 */
        sleep(3);
        del_semvalue();
    }
    exit(EXIT_SUCCESS);
}
Example #4
0
int main(int argc, char* argv[]) {
    int i;
    int pause_time;
    char op_char = 'O';
    srand((unsigned int)getpid());
    sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT);

    if (argc > 1) {
        if (!set_semvalue()) {
            fprintf(stderr, "Failed to initialize semaphore\n");
            exit(EXIT_FAILURE);
        }

        op_char = 'X';
        sleep(2);
    }

    /* Then we have a loop which enters and leaves the critical section ten times.
     There, we first make a call to semaphore_p which sets the semaphore to wait, as
     this program is about to enter the critical section. */

    for (i = 0; i < 10; i++) {
        if (!semaphore_p()) {
            exit(EXIT_FAILURE);
        }

        printf("%c", op_char);
        fflush(stdout);
        pause_time = rand() % 3;
        sleep(pause_time);
        printf("%c", op_char);
        fflush(stdout);

        /* After the critical section, we call semaphore_v, setting the semaphore available,
         before going through the for loop again after a random wait. After the loop, the call
         to del_semvalue is made to clean up the code. */

        if (!semaphore_v()) {
            exit(EXIT_FAILURE);
        }

        pause_time = rand() % 2;
        sleep(pause_time);
    }

    printf("\n%d - finished\n", getpid());

    if (argc > 1) {
        sleep(10);
        del_semvalue();
    }

    exit(EXIT_SUCCESS);
}
Example #5
0
int main(int argc, char *argv[])
{
	char message = 'X';
	int i = 0;

	key_t key;
	key = ftok("/var/httcsec",IPC_ID);
	//创建信号量
	printf("key:%d\n", (int)key);
	sem_id = semget(key, 1, 0666 | IPC_CREAT);

	if(argc > 1)
	{
		//程序第一次被调用,初始化信号量
		if(!set_semvalue())
		{
			fprintf(stderr, "Failed to initialize semaphore\n");
			exit(EXIT_FAILURE);
		}
		//设置要输出到屏幕中的信息,即其参数的第一个字符
		message = argv[1][0];
		sleep(2);
	}
	for(i = 0; i < 3; ++i)
	{
		//进入临界区
		if(!semaphore_p())
			exit(EXIT_FAILURE);
		//向屏幕中输出数据
		printf("..[%d]..lock\n", getpid());
		//清理缓冲区,然后休眠随机时间
		fflush(stdout);
		sleep(rand() % 5);
		//离开临界区前再一次向屏幕输出数据
		printf("..[%d]..unlock\n", getpid());
		fflush(stdout);
		//离开临界区,休眠随机时间后继续循环
		if(!semaphore_v())
			exit(EXIT_FAILURE);
		printf("..[%d]..waiting\n", getpid());
		fflush(stdout);
	}

	printf("\n%d - finished\n", getpid());

	if(argc > 1)
	{
		//如果程序是第一次被调用,则在退出前删除信号量
		sleep(3);
		del_semvalue();
	}
	exit(EXIT_SUCCESS);
}
Example #6
0
int main(int argc, char *argv[])
{
	int i;
	srand((unsigned int)getpid());
	sem_id = semget((key_t)4321, 1, 0666);
	printf("sem_id_%s = %d\n",argv[1], sem_id);
	if(sem_id < 0)
	{
		sem_id = semget((key_t)4321, 1, 0666|IPC_CREAT);
		printf("sem_id_2_%s = %d\n", argv[1] , sem_id);
	}

	if(argc > 1)
	{
		if(!set_semvalue())
		{
			fprintf(stderr, "Failed to initlize semaphore\n");
			exit(EXIT_FAILURE);
		}	

		op_char = argv[1];
// 		sleep(2);		
	}

	for(i = 0; i< 10; i++)	
	{
	/****************** P *********************/
		if(!semaphore_p())
			exit(EXIT_FAILURE);

		do_my_job(); //do something

	/****************** V *********************/
		if(!semaphore_v())
			exit(EXIT_FAILURE);


		pause_time = rand()%2;
// 		sleep(pause_time);

	}//for

	printf("\n%d - finished \n", getpid());

	if(argc > 1)
	{
// 		sleep(10);
		del_semvalue();
	}
	exit(EXIT_SUCCESS);
}
Example #7
0
int main(int argc, char *argv[])
{
	int i;
	int pause_time;
	char op_char='O';
	srand((unsigned int)getpid());
	sem_id = semget((key_t)4321, 1, 0666|IPC_CREAT);

	if(argc > 1)
	{
		if(!set_semvalue())
		{
			fprintf(stderr, "Failed to initlize semaphore\n");
			exit(EXIT_FAILURE);
		}	

		op_char = 'X';
		sleep(2);		
	}

	for(i = 0; i< 10; i++)
	{
		if(!semaphore_p())
			exit(EXIT_FAILURE);

		printf("%c is doing job\n", op_char);
		fflush(stdout);
		pause_time = rand()%3;
		sleep(pause_time);
		printf("%c is done\n", op_char);
		fflush(stdout);

		if(!semaphore_v())
			exit(EXIT_FAILURE);


		pause_time = rand()%2;
		sleep(pause_time);

	}//for

	printf("\n%d - finished \n", getpid());

	if(argc > 1)
	{
		sleep(10);
		del_semvalue();
	}
	exit(EXIT_SUCCESS);
}
Example #8
0
int main(int argc, char *argv[]) {
	int i;
	int pause_time;
	char op_char = 'O';

	// initialize the random seed
	srand( (unsigned int) getpid() );

	// creates a new semaphore (only 1) with modes + create if doesn't ex
	sem_id = semget( (key_t)1234, 1, 0666 | IPC_CREAT);

	// if invoked with parameters (must be the first invocation)
	if ( argc > 1 ) {
		if ( ! set_semvalue() ) {
			fprintf (stderr, "failed to init semaphore\n");
			exit (EXIT_FAILURE);
		}
		op_char = 'X';
		// gives time to start the second semaphore		
		sleep (2);
	}

	// normal run
	for ( i = 0 ; i < 10 ; i++ ) {
		if ( !semaphore_p() )
			exit (EXIT_FAILURE);
		printf ("%c", op_char); 
		fflush (stdout);
		
		pause_time = rand() % 3;
		sleep (pause_time);
		printf("%c", op_char);
		fflush (stdout);

		if ( ! semaphore_v() )
			exit (EXIT_FAILURE);
		pause_time = rand() % 2;
		sleep (pause_time);
	}

	printf ("\n%d - finished\n", getpid() );
	if (argc > 1 ) { 
		sleep (10);
		del_semvalue();
	}
	exit (EXIT_SUCCESS);
}
Example #9
0
File: sem1.c Project: jowishu/BLPv4
int main(int argc, char *argv[])
{
	int sem_id;
	char ch = 'O';
	int i, pause_time;

	srand((unsigned int)getpid());
	sem_id = semget((key_t)1234, 1, 0666|IPC_CREAT);
	if(sem_id < 0)
	{
		fprintf(stderr, "get semaphore id failed\n");
		exit(1);
	}

	if(argc > 1)
	{
		if(!set_semvalue(sem_id))
		{
			fprintf(stderr, "initialize semaphore failed\n");
			exit(1);
		}
		ch = 'X';
		sleep(2);
	}

	for(i = 0; i < 10; ++i)
	{
		if(!semaphore_p(sem_id))
		  exit(1);
		printf("%c", ch);
		fflush(stdout);
		pause_time = rand() % 3;
		sleep(pause_time);
		printf("%c", ch);
		fflush(stdout);
		if(!semaphore_v(sem_id))
		  exit(1);
	}

	if(argc > 1)
	{
		sleep(10);
		del_semvalue(sem_id);
	}
	exit(0);
}
int main(int argc, char *argv[]) {
    int i;
    int pause_time;
    char op_char = 'O';

    srand((unsigned int)getpid());
    
    sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT);

    // if there's an arg, set op_char to X and create the semaphore
    if (argc > 1) {
        if (!set_semvalue()) {
            fprintf(stderr, "Failed to initialize semaphore\n");
            exit(EXIT_FAILURE);
        }
        op_char = 'X';
        sleep(2);
    }

    // take turns locking, printing to stdout and flushing,
    // and then unlocking and waiting.
    for(i = 0; i < 10; i++) {        

        // lock around the printing and a short pause
        if (!semaphore_p()) exit(EXIT_FAILURE);
        printf("%c", op_char);fflush(stdout);
        pause_time = rand() % 3;
        sleep(pause_time);
        printf("%c", op_char);fflush(stdout);
        if (!semaphore_v()) exit(EXIT_FAILURE);
        
        // then do a random pause while unlocked
        pause_time = rand() % 2;
        sleep(pause_time);
    }    

    printf("\n%d - finished\n", getpid());

    // it's very important to delete the semaphore you created!
    if (argc > 1) {    
        sleep(10);
        del_semvalue();
    }
        
    exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[])
{
	int i;
	int pause_time;
	char op_char = '0';

	srand((unsigned int)getpid());
	// 创建信号量
	sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT);
	if (argc > 1) {
		// 当参数大于1个时候, 初始化信号量, 让op_char 为 'X'
		if (!set_semvalue()) {
			fprintf(stderr, "Failed to initialize semaphore\n");
			exit(EXIT_SUCCESS);
		}
		op_char = 'X';
		sleep(2);
	}
	for (i = 0; i < 10; i++) {
		// 执行p操作, 减1
		if (!sem_operation_p()) exit(EXIT_SUCCESS);
		printf("%c", op_char);fflush(stdout);
		// 休息(随机数,(0, 3])s
		pause_time = rand() % 3;
		sleep(pause_time);
		printf("%c", op_char);fflush(stdout);
		// 执行v操作, 加1
		if (!sem_operation_v()) exit(EXIT_SUCCESS);
		// 休息(随机数,(0, 2])s
		pause_time = rand() % 2;
		sleep(pause_time);
	}

	printf("\n%d - finished\n", getpid());

	if (argc > 1) {
		sleep(10);
		del_semvalue();
	}

	exit(EXIT_SUCCESS);
}
Example #12
0
File: sem1.c Project: bryan0806/SP
int main(int argc,char *argv[]){
	int i;
	int pause_time;
	char op_char='O';

	srand((unsigned int)getpid());

	sem_id = semget((key_t)1234,1,0666|IPC_CREAT);// 產生一個新號誌 或者根據key 取得一個已存在的號誌 666為設定權限
	if(argc >1){ // 假設第一次執行時 使用參數
		if(!set_semvalue()){  // setctl回傳-1時(發生錯誤)
			fprintf(stderr,"Failed to initialize semaphore\n");	
			exit(EXIT_FAILURE);
		}
		op_char='X';
		sleep(2);
	}

	/* 然後進入迴圈 進出入 "critical section" 十次
 *  在那裡 首先先呼叫semaphore_p 讓即將進入critical section 的semaphore等待*/ 	
	for(i=0;i<10;i++){
		if(!semaphore_p()) exit(EXIT_FAILURE);
		printf("%c",op_char);fflush(stdout);
		pause_time=rand()%3;
		sleep(pause_time);
		printf("%c",op_char);fflush(stdout);
/* 在critical section 之後 呼叫semaphore_v
 * 再進去for loop 之前 等待一段亂數時間 然後del sem 結束*/
		if(!semaphore_v()) exit(EXIT_FAILURE);
		
		pause_time=rand()%2;
		sleep(pause_time);	
		}
		
		printf("\n%d - finished\n",getpid());

		if(argc>1){
			sleep(10);
			del_semvalue();
		}
		exit(EXIT_SUCCESS);
}
Example #13
0
/*
//------------------------------------------------------------------------------------------------------
//     Allocate shraed memory ,set semaphore,wakeup audio server
//    
//------------------------------------------------------------------------------------------------------
*/
static int preinit(sh_audio_t *sh)
{
        #ifndef  EngineMode 
	      union smc *sc;
	      long curr_codec;
	      #endif

         {

        #ifndef  EngineMode 
        if(sh->samplesize==2)
      	{
   	      sh->sample_format=AF_FORMAT_S16_LE; //packing as 2 bytes
         
   	  }else  if(sh->samplesize==1)
   	  {
   	      sh->sample_format=AF_FORMAT_U8; //packing as 1 bytes
         
   	  }else if(sh->samplesize==4)
        {
    	 
    	     sh->sample_format=AF_FORMAT_S32_LE; //packing as 4 bytes
      
        }
   
        #endif 

         sh->audio_out_minsize = BLOCKS_PER_LOOP*2*sh->samplesize; 

         }
#ifndef  EngineMode 
#ifdef AD_SHM_REWRITE
	sm_com_id = get_first_shared_mem_id(KEY_SM_COM, SM_COM_SIZE);
	if(sm_com_id < 0)
		sm_com_id = get_shared_mem_id(KEY_SM_COM, SM_COM_SIZE);  //get shared memory ID
	if(sm_com == NULL)
	{
		if ((sm_com = allocate_share_mem(sm_com_id))==NULL) 	   //allocate shared memory ( command )
			return 0;
	}
#else
	sm_com_id = get_shared_mem_id(KEY_SM_COM, SM_COM_SIZE);  //get shared memory ID
	if ((sm_com = allocate_share_mem(sm_com_id))==NULL) 	   //allocate shared memory ( command ) 
		return 0;
#endif

	      id = get_semaphore_id();                                 //get semaphore ID 
	
	      if (!reset_semvalue(id, 0)){                             //reset semaphore 
		      return 0;
 	      }

	      sc = (union smc *)sm_com;                     

	      sc->magic.magic_num = PLAYER_MAGIC;           
	      curr_codec = APE_ID;                                     //inform server what kind of coded to be used.

	      sc->magic.codec_id = curr_codec;                         
   	      if (!semaphore_v(id, 1))                                   //wakeup server!
		     return 0;	

	      if (!wait_server(sc)){                                    //wait for server's response
		      deallocate_share_mem(sm_com);	
#ifndef AD_SHM_REWRITE
		      shmctl(sm_com_id, IPC_RMID, 0);
#endif
		      del_semvalue(id, 0);
		      printf("Audio server crash \n");
		      return 0;
	      }	

	      if (sc->magic.codec_id != curr_codec){                   //check codec 
		       printf("Unsuppoted codec\n");
		       return 0;		
	      }
	
   
         #endif

         csd_avail_num = res_num =  0;
        

      return 1;
}
/*
//------------------------------------------------------------------------------------------------------
//     Allocate shraed memory ,set semaphore,wakeup audio server
//    
//------------------------------------------------------------------------------------------------------
*/
static int preinit(sh_audio_t *sh)
{
	aserver_pid = 0;
         #ifndef  EngineMode 
	      union smc *sc;
	      long curr_codec;
	      #endif

         {
         sh->audio_out_minsize = 320; 

         }
#ifndef  EngineMode 
#ifdef AD_SHM_REWRITE
	sm_com_id = get_first_shared_mem_id(KEY_SM_COM, SM_COM_SIZE);
	if(sm_com_id < 0)
		sm_com_id = get_shared_mem_id(KEY_SM_COM, SM_COM_SIZE);  //get shared memory ID
	if(sm_com == NULL)
	{
		if ((sm_com = allocate_share_mem(sm_com_id))==NULL) 	   //allocate shared memory ( command )
			return 0;
	}
#else
	sm_com_id = get_shared_mem_id(KEY_SM_COM, SM_COM_SIZE);  //get shared memory ID
	if ((sm_com = allocate_share_mem(sm_com_id))==NULL) 	   //allocate shared memory ( command ) 
		return 0;
#endif

	      id = get_semaphore_id();                                 //get semaphore ID 
	
	      if (!reset_semvalue(id, 0)){                             //reset semaphore 
		      return 0;
 	      }

	      sc = (union smc *)sm_com;                     

	      sc->magic.magic_num = PLAYER_MAGIC;           
	      curr_codec = AMRNB_ID;                                     //inform server what kind of coded to be used.

	      sc->magic.codec_id = curr_codec;                         
   	      if (!semaphore_v(id, 1))                                   //wakeup server!
		     return 0;	

	      if (!wait_server(sc)){                                    //wait for server's response
		      deallocate_share_mem(sm_com);	
#ifndef AD_SHM_REWRITE
		      shmctl(sm_com_id, IPC_RMID, 0);
#endif
		      del_semvalue(id, 0);
		      printf("Audio server crash \n");
		      return 0;
	      }	

	      if (sc->magic.codec_id != curr_codec){                   //check codec 
		       printf("Unsuppoted codec\n");
		       return 0;		
	      }
	
   
         #endif

        aserver_pid = sc->pinit.pid;

      return 1;
}
Example #15
0
int main(void)
{
	// Shared memory. shm1 used for circular buffer, shm2 used for metadata
	int shmid, shmid2;
	void *shared_memory1 = (void *)0;
	void *shared_memory2 = (void *)0;
 	struct buffer_block *shared_buffer;
 	struct metadata *shared_metadata;
 	int buffer_index;
  
  // Semaphores. S: mutual exclusion. N: synch producer before consumer. E: buffer space
  int sem_S_id, sem_N_id, sem_E_id;

  // Output file
  int file_out;
  int nWrite_file; 	// Num bytes written to file

	
	/* Creating shared memory (circular buffer) */
	if (init_shm_circularBuffer(SHM_KEY, &shmid, &shared_memory1) == -1) {
		exit(EXIT_FAILURE);
	}
	printf("[C] Shared Memory (circular buffer) attached at: %p. shmid: %d\n", (int*)shared_memory1, shmid);	
	shared_buffer = (struct buffer_block*) shared_memory1;			// Assigns shared_memory segment to shared_buffer
	buffer_index = 0;

	/* Creating shared memory (metadata) */
	if (init_shm_metadata(SHM2_KEY, &shmid2, &shared_memory2) == -1) {
		exit(EXIT_FAILURE);
	}
	printf("[C] Shared Memory (metadata) attached at %p, shmid: %d\n", (int*)shared_memory2, shmid2);
	shared_metadata = (struct metadata*) shared_memory2;						// Assigns shared_memory2 segment to shared_metadata

	printf(" - - - - - - - - - - - - - - - - - - - - - - \n");
	
	/* Creating semaphores */
	sem_S_id = semget((key_t)SEM_S_KEY, 1, 0666 | IPC_CREAT);
	sem_N_id = semget((key_t)SEM_N_KEY, 1, 0666 | IPC_CREAT);
	sem_E_id = semget((key_t)SEM_E_KEY, 1, 0666 | IPC_CREAT);

  // Open file for writing
  open_file_write(&file_out);
  // Wait for producer first so that the number of bytes read from file is known
  printf("[C] Waiting for producer to get input file size...\n");
  semaphore_wait(sem_N_id);
  printf("[C] File size information from producer: %d bytes\n", shared_metadata->file_byte_count);

  /* Start time difference. For Bonus */
  struct timeval start_time, end_time;
  gettimeofday(&start_time, NULL);


  /* Copy contents from shared memory to the output file */
  printf("[C] Reading from shared memory and writing to file...\n");
  nWrite_file = 0;
	while (nWrite_file < shared_metadata->file_byte_count) {
		semaphore_wait(sem_N_id);
		semaphore_wait(sem_S_id);
		nWrite_file += copy_to_file(file_out, shared_buffer, &buffer_index);
		semaphore_signal(sem_S_id);
		semaphore_signal(sem_E_id);
		printf("[C]	Bytes written to file: %d\n", nWrite_file);
	}

	printf(" - - - - - - - - - - - - - - - - - - - - - - \n");
	printf("[C] Total Bytes written to '%s': %d\n", FILE_OUT, nWrite_file);

	/* Calculate time difference. For Bonus */
	gettimeofday(&end_time, NULL);
	printf(">> %ld microseconds\n", ((end_time.tv_sec * MICRO_SEC_IN_SEC + end_time.tv_usec) - (start_time.tv_sec * MICRO_SEC_IN_SEC + start_time.tv_usec)));

	/* Cleanup */
	// Close file
	if (close(file_out) == -1) {
		fprintf(stderr, "[C] File close failed\n");
	}
	// Shared memory is detached and deleted
  if (shmdt(shared_memory1) == -1) {
    fprintf(stderr, "[C] shmdt failed\n");
    exit(EXIT_FAILURE);
  }
  if (shmctl(shmid, IPC_RMID, 0) == -1) {
    fprintf(stderr, "[C] shmctl(IPC_RMID) failed\n");
    exit(EXIT_FAILURE);
  }
  if (shmdt(shared_memory2) == -1) {
    fprintf(stderr, "[C] shmdt failed\n");
    exit(EXIT_FAILURE);
  }
  if (shmctl(shmid2, IPC_RMID, 0) == -1) {
    fprintf(stderr, "[C] shmctl(IPC_RMID) failed\n");
    exit(EXIT_FAILURE);
  }

  // Delete Semaphores
  del_semvalue(sem_S_id);
  del_semvalue(sem_N_id);
  del_semvalue(sem_E_id);

	exit(EXIT_SUCCESS);
}
Example #16
0
int main(int argc, char *argv[])
{
	int i;
	char op_char = 'O';
	int pause_time;

	srand(getpid());

	sem_id = semget((key_t)123, 1, 0666 | IPC_CREAT); 
	if (-1 == sem_id)
	{
		perror("Failed to create semaphore. ");
		printf("Error: %s\n", strerror(errno));
		exit(1);
	}

	if (argc > 1)
	{
		if (!set_semvalue())
		{
			fprintf(stderr, "Failed to initialize semaphore.\n");
			exit(EXIT_FAILURE);
		}

		op_char = 'X';
		sleep(2);
	}

	for (i = 0; i < 10; ++i)
	{
		if (!sem_p())
		{
			exit(EXIT_FAILURE);
		}

		printf("%c", op_char);
		fflush(stdout);
		pause_time = rand() % 3;
		sleep(pause_time);
		printf("%c", op_char);
		fflush(stdout);
		
		if (!sem_v())
		{
			exit(EXIT_FAILURE);
		}

		pause_time = rand() % 2;
		sleep(pause_time);
	}

	printf("\n%d - finished\n", getpid());

	if (argc > 1)
	{
		sleep(10);
		del_semvalue();
	}

	exit(EXIT_SUCCESS);
}
Example #17
0
/************************************************************
 * function:  create or open the shared memory.
 * iscreated: 1, to create the shm; 0, only to open the shm.
 * mqsize:    the count of the items
 * itemsize:  the size of an item (bytes)
 * return:    0, correct; others, error number.
 ***********************************************************/
int shmmq_open(int iscreated, int mqsize, int itemsize)
{
	int nflag;
	int ret = 0;

	/* Initial semaphore */
	g_s_semid = get_semvalue((key_t)SEM_KEY);
	if (-1 == g_s_semid) {
		return ERROR_GET_SEMVALUE;
	}
	if (iscreated && -1 == set_semvalue(g_s_semid)) {
		return ERROR_SET_SEMVALUE;
	}

	if (-1 == semaphore_p(g_s_semid)) {
		return ERROR_SEMAPHORE_P;
	}
	while (1) 
	{
		if (iscreated) {
			nflag = 0666 | IPC_CREAT;
		} else {
			nflag = 0666;
		}

		g_s_mqsize = (mqsize <= 0) ? DEFAULT_MQ_SIZE : mqsize;
		g_s_itemsize = (itemsize <= 0) ? DEFAULT_ITEM_SIZE : itemsize;

		/* Initial shared memory */
		g_s_shmid = shmget((key_t)SHM_KEY, 
			g_s_mqsize * g_s_itemsize + DEFAULT_HEAD_SIZE,
			nflag);
		if (-1 == g_s_shmid) {
			ret = ERROR_SHMGET;
			break;
		}

		g_s_pbase = shmat(g_s_shmid, NULL, 0);
		if ((void *)-1 == g_s_pbase) {
			g_s_pbase = NULL;
			ret = ERROR_SHMAT;
			break;
		}

		g_s_phead = (shmmq_head*)g_s_pbase;
		g_s_pcontent = g_s_pbase + DEFAULT_HEAD_SIZE;

		/* Initial head of the shared memory  */
		if (iscreated) {
			g_s_phead->enq_pos = -1;
			g_s_phead->deq_pos = -1;
		}
		break;
	}
	if (ret && iscreated) {
		if (g_s_shmid >= 0) shmctl(g_s_shmid, IPC_RMID, 0);
		semaphore_v(g_s_semid);
		del_semvalue(g_s_semid);
		return ret;
	}

	if (-1 == semaphore_v(g_s_semid)) {
		return ERROR_SEMAPHORE_V;
	}

	return ret;
}
Example #18
0
int main()
{
	struct timeval start, end;
    int running = 1;
    void *shared_memory = (void *)0;
    struct shared_use_st *shared_stuff;
    int shmid;

    srand((unsigned int)getpid());

    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);
    
	if (!set_available()| !set_empty()) {
            fprintf(stderr, "Failed to initialize semaphore\n");
            exit(EXIT_FAILURE);
        }

    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,
 which then prints out any text in written_by_you. The loop continues until end is found
 in written_by_you. The call to sleep forces the consumer to sit in its critical section,
 which makes the producer wait. */

    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

	//timer start
	gettimeofday(&start, NULL);
	for (int i = 0; i < 100000; i++){}
	
    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){
		
		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);		

		
		//timer finished
		gettimeofday(&end, NULL);
		printf("\nElapsed Time: %ld micro sec\n", ((end.tv_sec * MICRO_SEC_IN_SEC + end.tv_usec)- (start.tv_sec * MICRO_SEC_IN_SEC + start.tv_usec)));
		
		sleep(4);
		del_semvalue();
		
		/*
		//timer finished
		gettimeofday(&end, NULL);
		printf("\nElapsed Time: %ld micro sec\n", ((end.tv_sec * MICRO_SEC_IN_SEC + end.tv_usec)- (start.tv_sec * MICRO_SEC_IN_SEC + start.tv_usec)));
		*/
		exit(EXIT_SUCCESS);
		
		}
		else{
		empty_p();	
		
 		shared_stuff->msgs[index].written = 128;
		//printf("writte\n");
		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;  

		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);
    }

	//del_semvalue();

    exit(EXIT_SUCCESS);
}
Example #19
0
int main()
{
    signal (SIGTERM, out);
    signal (SIGINT, out);

    int shmid;
    /* искать сегмент, соответствующий ключу key*/
    shmid = shmget((key_t)1234, sizeof(struct memFormat), 0666);

    if (shmid == -1)  {perror("shmget");return 0;}

    shared_memory = shmat(shmid, (void *)0, SHM_RDONLY);
    if (shared_memory == (void *)-1) {perror("shmat");return 0;}

    int sem_id = createSem(1,12345);
    if(sem_id==-1) {perror("createSem"); return 0;}
	
    if(set_semvalue(sem_id,0)==-1) {perror("set_semvalue"); return 0;}

    semaphore_p(sem_id);
    memcpy(&memf,shared_memory, sizeof(struct memFormat)); 
    semaphore_v(sem_id);

    if (shmdt(shared_memory) == -1) {perror("shmat"); return 0;}

    int size = sizeof(struct memFormat)+(memf.max*memf.sizeItem);
    printf("Moniotr attache mem size: %d + %d=%d",sizeof(struct memFormat),(memf.max*memf.sizeItem),size);

    shmid = shmget((key_t)1234, size, 0666);

    if (shmid == -1)  {perror("shmget2");return 0;}

    shared_memory = shmat(shmid, (void *)0, SHM_RDONLY);
    if (shared_memory == (void *)-1) {perror("shmat2");return 0;}

    pitem = (int*)shared_memory+sizeof(struct memFormat);
    printf("Monitor memory attached at %p,data attached at %p\n", shared_memory,pitem);

    printf("memory pid %d:\n sizeItem %d, count %d, max %d",memf.pidMaster,memf.sizeItem,memf.count,memf.max);
    sleep(1);
    while(bOut==false) 
    {        
	pitem = (int*)shared_memory+sizeof(struct memFormat);

	delay(500);
	
	int count1=0;

	if(!semaphore_p(sem_id)) {perror("semaphore_p");break;}

	memcpy(&memf,shared_memory, sizeof(struct memFormat));	
	for(int vi=0;vi<memf.count;vi++)
	{
		if(*pitem==1) count1++;
		//printf("%d.",*pitem);
		pitem++;
	}

	if(!semaphore_v(sem_id)) {perror("semaphore_v");break;}
	printf("\nnumber '1': %d.",count1);          
        
    }

    if (shmdt(shared_memory) == -1) {perror("shmat2");}
    del_semvalue(sem_id,0);
    printf("\nExit...\n");
}
Example #20
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);
}