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

C++ shmat函数代码示例

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

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



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

示例1: open

int TDebugLog::log_open(int level, std::string log_path, 
	std::string log_name, int max_size, int num, key_t shm_key)
{
	_log_path  = log_path;
	_log_name  = log_name;
	_log_level = level;
	_log_size  = max_size;
	_log_num   = num;

	if (_log_file != -1)
		return 1;

	std::string filename = log_path + "/" + log_name + ".log";
	_log_file = open(filename.c_str(), O_CREAT | O_APPEND | O_RDWR, 0644);
	if (_log_file == -1)
		return -1;

	// 创建锁
	std::string lockname = log_name + "_log";
	_lock = new CMSem(lockname.c_str(), 1);
	// 创建共享内存
	_shm_id = shmget(shm_key, BUFFER_SIZE + sizeof(int), IPC_CREAT | 0644);
	if (_shm_id < 0)
	{
		perror("shmget");
		return -2;
	}
	_buf = (log_buffer *) shmat(_shm_id, 0, 0);
	if (_buf == (void *) -1)
	{
		perror("shmat");
		return -3;
	}

	struct sigaction act, old_int, old_usr1;
	sigset_t blk, old;
	// 注册信号
	act.sa_handler = sig_handler;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	sigaction(SIGINT, &act, &old_int);
	sigaction(SIGUSR1, &act, &old_usr1);
	// 阻塞SIGUSR1
	sigaddset(&blk, SIGUSR1);
	sigprocmask(SIG_BLOCK, &blk, &old);
	stop = false;
	// 启动日志进程
	if ((_log_pid = fork()) == 0)
	{
		log_proc();
		exit(0);
	}
	// 恢复信号处理
	sigprocmask(SIG_SETMASK, &old, NULL);
	sigaction(SIGUSR1, &old_usr1, NULL);
	sigaction(SIGINT, &old_int, NULL);

	if (_log_pid < 0)
		return -4;

	return 0;
}
开发者ID:zhc105,项目名称:piClock,代码行数:62,代码来源:m_log.cpp


示例2: getpagesize

/* helper function for memory-based channels */
static struct mpc_link *__minipc_memlink_create(struct mpc_link *link)
{
	void *addr = NULL;
	long offset;
	int memsize, pid, ret;
	int pagesize = getpagesize();
	int pfd[2];
	char msg;

	memsize = (sizeof(struct mpc_shmem) + pagesize - 1) & ~pagesize;

	/* Warning: no check for trailing garbage in name */
	if (sscanf(link->name, "shm:%li", &offset)) {
		ret = shmget(offset, memsize, IPC_CREAT | 0666);
		if (ret < 0)
			return NULL;
		addr = shmat(ret, NULL, SHM_RND);
		if (addr == (void *)-1)
			return NULL;
		link->flags |= MPC_FLAG_SHMEM;
	}

	/* Warning: no check for trailing garbage in name -- hex mandatory */
	if (sscanf(link->name, "mem:%lx", &offset)) {
		int fd = open("/dev/mem", O_RDWR | O_SYNC);

		if (fd < 0)
			return NULL;
		addr = mmap(0, memsize, PROT_READ | PROT_WRITE, MAP_SHARED,
			    fd, offset);
		close(fd);
		if (addr == (MAP_FAILED))
			return NULL;
		link->flags |= MPC_FLAG_DEVMEM;
	}
	link->memaddr = addr;
	link->memsize = memsize;
	if (link->flags & MPC_FLAG_SERVER)
		memset(addr, 0, sizeof(struct mpc_shmem));

	/* fork a polling process */
	if (pipe(pfd) < 0)
		goto err_unmap;
	switch ( (pid = fork()) ) {
	case 0: /* child */
		close(pfd[0]);
		__minipc_child(addr, pfd[1], link->flags);
		exit(1);
	default: /* father */
		close(pfd[1]);
		link->ch.fd = pfd[0];
		link->pid = pid;
		/* Before operating, wait for the child to ping us */
		read (pfd[0], &msg, 1); /* must be '-' ... check? */
		/* Now turn it into non-blocking (we poll(2)) */
		fcntl(pfd[0], F_SETFL, fcntl(pfd[0], F_GETFL) | O_NONBLOCK);
		return link;
	case -1:
		break; /* error... */
	}
	close(pfd[0]);
	close(pfd[1]);
 err_unmap:
	if (link->flags & MPC_FLAG_SHMEM)
		shmdt(link->memaddr);
	if (link->flags & MPC_FLAG_DEVMEM)
		munmap(link->memaddr, link->memsize);
	return NULL;

}
开发者ID:a-rubini,项目名称:mini-rpc,代码行数:71,代码来源:minipc-core.c


示例3: main

int main()
{
  key_t key = ftok("./id",10);

  //Creation semaphore
  int semid = semget(key,2,IPC_CREAT|IPC_EXCL|0666);
  if( semid < 0 )
    {
      semid = semget(key,2,0666);
    }
  else
    {
      union senum init;
      //Semaphore pour le boss
      init.val = 0;
      if(semctl(semid,0,SETVAL,init) == -1)
	{
	  printf("probleme init");
	}
      //Semaphore pour les employers
      init.val = 2;
      if(semctl(semid,1,SETVAL,init) == -1)
	{
	  printf("probleme init");
	}
    }

  //Creation memoire partagé
  int shmid = shmget(key,sizeof(Message),IPC_CREAT|0666);

  Message* mess;
  while(1)
    {
      mess = (Message *)shmat(shmid, NULL, NULL);
      
      printf("Ecrivez votre message\n");
      scanf("%s",mess->mess);
      if(strcmp(mess->mess,"exit") == 0)
	{
	  break;
	}
      
      if( shmdt(mess) < 0 )
	{
	  printf("erreur liberation memoire partagé\n");
	  exit(0);
	}
      
      struct sembuf V;
      V.sem_num = 0;
      V.sem_op = +1;
      V.sem_flg = NULL;
      
      semop(semid,&V,1);
      
      struct sembuf op[] = 
	{
	  {(u_short)1,(short)0,NULL},
	  {(u_short)0,(short)-1,NULL},
	  {(u_short)1,(short)+2,NULL}
	};
      
      semop(semid,op,3);
      
    }

  shmctl(shmid,IPC_RMID,NULL);
  semctl(semid,0,IPC_RMID);
      
  return EXIT_SUCCESS;
}
开发者ID:roknus,项目名称:FMIN104,代码行数:71,代码来源:boss.c


示例4: main

int main(int argc, char *argv[])
{
    int c, status;
    char *src;
    buf_s *in;
    struct sigaction sa;
    sym_record_s *rec, *recb;
    pthread_t req_thread;
    sigset_t mask;
    
    if(argc > 1) {
        src = readfile(argv[1]);
        parse(src);
        closefile();
    }
    else {
        src = readfile("test");
        parse(src);
        closefile();
    }
    
    name = "ap";
    name_stripped = "ap";
    name_len = sizeof("ap")-1;
    
    if(access("out/", F_OK)) {
        if(errno == ENOENT)
            mkdir("out", S_IRWXU);
        else {
            perror("Directory Access");
            exit(EXIT_FAILURE);
        }
    }
    
    logfile = fopen("out/ap", "w");
    if(!logfile) {
        perror("Error Creating file for redirection");
        exit(EXIT_FAILURE);
    }
    
    sa.sa_handler = sigUSR1;
    sa.sa_flags = SA_RESTART;
    sigemptyset(&sa.sa_mask);
    status = sigaction(SIGUSR1, &sa, NULL);
    if(status < 0) {
        perror("Error installing handler for SIGUSR1");
        exit(EXIT_FAILURE);
    }
    
    sa.sa_handler = sigALARM;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);
    status = sigaction(SIGALRM, &sa, NULL);
    if(status < 0) {
        perror("Error installing handler for SIGTERM");
        exit(EXIT_FAILURE);
    }

    shm_mediums = shmget(SHM_KEY_S, sizeof(*mediums), IPC_CREAT|SHM_R|SHM_W);
    if(shm_mediums < 0) {
        perror("Failed to set up shared memory segment");
        exit(EXIT_FAILURE);
    }
    
    mediums = shmat(shm_mediums, NULL, 0);
    if(mediums == (medium_s *)-1) {
        perror("Failed to attached shared memory segment.");
        exit(EXIT_FAILURE);
    }
    mediums->isbusy = false;
    
    shm_mediumc = shmget(SHM_KEY_C, sizeof(*mediumc), IPC_CREAT|SHM_R|SHM_W);
    if(shm_mediumc < 0) {
        perror("Failed to set up shared memory segment");
        exit(EXIT_FAILURE);
    }
    
    mediumc = shmat(shm_mediumc, NULL, 0);
    if(mediumc == (medium_s *)-1) {
        perror("Failed to attached shared memory segment.");
        exit(EXIT_FAILURE);
    }
    mediumc->isbusy = false;
    
    status = pthread_create(&req_thread, NULL, process_request, NULL);
    if(status) {
        perror("Failure to set up thread");
        exit(EXIT_FAILURE);
    }
    
    sigemptyset(&mask);
    sigaddset(&mask, SIGUSR2);
    status = pthread_sigmask(SIG_BLOCK, &mask, NULL);
    if(status) {
        perror("Failure to mask SIGUSR2 in parent thread.");
        exit(EXIT_FAILURE);
    }

    process_tasks();
    
//.........这里部分代码省略.........
开发者ID:jonathanhamm,项目名称:csma,代码行数:101,代码来源:ap.c


示例5: getSharedMemPtr

void * getSharedMemPtr(key_t key)
{
  FILE * fp;

  shmid = shmget(key,
                 sizeof(pthread_mutex_t) + sizeof(pthread_once_t),
                 IPC_CREAT | IPC_EXCL | 0x1b6);
  
  if( shmid < 0 )
  {
    switch( errno )
    {
      case EEXIST:
    printf("Could not create shared mem.\n");
      printf("Will attempt to find it.\n");
      
      shmid = shmget(key,
          sizeof(pthread_mutex_t) + sizeof(pthread_once_t),
          0x1b6);
      break;
    }
      
      if(0 > shmid)
  {
    printf("\tCouldnt find it either\n");
  }

      else
  {
    
    fp = fopen("MutextestFile.txt", "r+");
          fclose(fp);  
    
    myLine = PROG2;
    printf("\tFound shared memory");
    void * const poSharedMem = shmat(shmid, NULL, 0);
    
    if(((void *)-1) == poSharedMem)
      {
        printf("Could not attatch shared memory to address space.\n");
        return  NULL;
      }
    else
      {
        //printf("Shared memory attached and marked for deletion.\n");
        //shmctl(shmid, IPC_RMID, NULL);
        printf("Shared memory attached\n");
        return poSharedMem;       
      }
  }
    } 
  else
    {
      fp = fopen("MutextestFile.txt", "w+");
      fclose(fp);

      myLine = PROG1;
      printf("Shared memory created.\n");
      
      void * const poSharedMem = shmat(shmid, NULL, 0);
      
      if(((void *)-1) == poSharedMem)
  {
    printf("Could not attatch shared memory to address space.\n");
    return  NULL;
  }
      else
  {
    //printf("Shared memory attached and marked for deletion.\n");
    //shmctl(shmid, IPC_RMID, NULL);
    printf("Shared memory attached\n");
    return  poSharedMem;
  }
    }

  return  NULL;
}
开发者ID:roadnarrows-robotics,项目名称:librnr,代码行数:77,代码来源:shm.c


示例6: main

int main(int argc, char** argv)
{
    signal(SIGINT, shutdown);
    int philosopherCount = atoi(argv[1]);
    int philId = atoi(argv[2]);
    int semSet = atoi(argv[3]);
    int shmId = atoi(argv[4]);
    mem = shmat(shmId, NULL, 0);
    srand(time(0) ^ philId);

    while(true)
    {
        int nextPhilId = (philId + 1) % philosopherCount;
        struct sembuf sops[4]; /* nsops increased from 2 to 4 to cause wait operation to be fully atomic */
        sops[0].sem_num = philId;        /* Operate on semaphore philId */
        sops[0].sem_op = 0;         /* Wait for value to equal 0 */
        sops[0].sem_flg = 0;

        sops[1].sem_num = philId;        /* Operate on semaphore philId */
        sops[1].sem_op = 1;         /* Increment value by 1 */
        sops[1].sem_flg = 0;

        /* Following lines were commented out to atomically lock both semaphores and queue
         * processes requests - it is similar to arbitrator solution, but due to usage of two
         * atomic semaphores doesn't introduce additional wait associated with global arbitrator.
         * Solution protects processes from deadlocking, but doesn't fully prevent starvation. */

        /*printf("philosopher %d Waits for first fork\n", philId);
        if(semop(semSet, sops, 2) != 0)
            perror("");*/

        sops[2].sem_num = nextPhilId;        /* Operate on semaphore nextPhilId */
        sops[2].sem_op = 0;         /* Wait for value to equal 0 */
        sops[2].sem_flg = 0;

        sops[3].sem_num = nextPhilId;        /* Operate on semaphore nextPhilId */
        sops[3].sem_op = 1;         /* Increment value by 1 */
        sops[3].sem_flg = 0;

        mem[philId] = 'W';
        printf("\33[2Kphilosopher %d Waits for forks\n", philId);
        if(semop(semSet, sops, 4) != 0)  /* nsops increased from 2 to 4 to make wait atomic */
        {
            char buffer[100] = {};
            sprintf(buffer, "philosopher id %d reports: ", philId);
            perror(buffer);
        }
        mem[philId] = 'E';

        sops[0].sem_num = philId;        /* Operate on semaphore philId */
        sops[0].sem_op = -1;         /* Decrement value by 1 */
        sops[0].sem_flg = 0;

        sops[1].sem_num = nextPhilId;        /* Operate on semaphore nextPhilId */
        sops[1].sem_op = -1;         /* Decrement value by 1 */
        sops[1].sem_flg = 0;

        printf("\33[2Kphilosopher %d Eats for a while\n", philId);
        usleep(2e6 + rand() % 1000 * 1000);
        mem[philId] = 'M';
        if(semop(semSet, sops, 2) != 0)
        {
            char buffer[100] = {};
            sprintf(buffer, "philosopher id %d reports: ", philId);
            perror(buffer);
        }

        printf("\33[2Kphilosopher %d Meditates for a while\n", philId);
        fflush(stdout);
        usleep(4e6 + rand() % 1000 * 1000);
    }

    return 0;
}
开发者ID:interj,项目名称:sso,代码行数:74,代码来源:philosopher.c


示例7: main

int main()
{
    printf("hell\n");
    signal(SIGUSR1, sigusr1);
    char pathname[1000];
    getwd(pathname);

    //creating the write-semaphore(two)
    key_t keyw = ftok(pathname, 'A');
    write_sem_id = semget(keyw, 2, IPC_CREAT|0666);
    if(write_sem_id < 0)
    {
        printf("Semaphore init error\n");
        exit(1);
    }
    printf("%d %d", sem_val(write_sem_id, 0), sem_val(write_sem_id, 1));

    //acquire semaphore to register the process..
    sem_change(write_sem_id, 0, -1);
    printf("%d %d", sem_val(write_sem_id, 0), sem_val(write_sem_id, 1));
    //accessing shared memory for storing process IDs of max 50 processes
    //the first memory location stores the current number of active processes
    key_t pid_shm_key = ftok(pathname, 'C');
    int pid_shm_id = shmget(pid_shm_key, 60*sizeof(int), IPC_CREAT|0666);
    if(pid_shm_id < 0)
    {
        printf("shmget error\n");
        exit(1);
    }
    pids = (int*)shmat(pid_shm_id, NULL, 0);
    *(pids) = *(pids) + 1;  //increase the number of active processes..
    ref_id = *(pids);
    *(pids + ref_id) = getpid();
    printf("Registered PID of this process: %d\nThe reference ID for this process is: %d\n", getpid(), ref_id);

    sem_change(write_sem_id, 0, 1);


    //creating shared memory for storing message contents
    //can store maximum of 10000 characters.
    //Each process/client(max 50) has its own memory-block
    //0th block is server's. Rest are allocated according to reference IDs..

    key_t msg_shm_key = ftok(pathname, 'D');
    int msg_shm_id = shmget(msg_shm_key, 60*sizeof(struct message), IPC_CREAT|0666);
    if(msg_shm_id < 0)
    {
        printf("shmget error\n");
        exit(1);
    }
    m = (struct message *)shmat(msg_shm_id, NULL, 0);
    if(m == (struct message*)-1)
    {
        printf("shmat error\n");
        exit(1);
    }

    //creating tot_read_count
    key_t count_shm_key = ftok(pathname, 'H');
    int count_shm_id = shmget(count_shm_key, sizeof(int), IPC_CREAT|0666);
    if(count_shm_id < 0)
    {
        printf("shmget error\n");
        exit(1);
    }
    count = (int*)shmat(count_shm_id, NULL, 0);
    if(count == (int*)-1)
    {
        printf("shmat error\n");
        exit(1);
    }
    printf("%d %d %d %d %d %d\n", write_sem_id, pid_shm_id, msg_shm_id,  count_shm_id);
    printf("%d %d", sem_val(write_sem_id, 0), sem_val(write_sem_id, 1));
    sleep(5);
    pthread_create(&reader, NULL, (void *)&read_thread, NULL);
    pthread_create(&writer, NULL, (void *)&write_thread, NULL);

    pthread_join(reader, NULL);
    pthread_join(writer, NULL);
    return 0;
}
开发者ID:rohitranjan1994,项目名称:MultiThreaded-Server,代码行数:81,代码来源:client2.c


示例8: main

int main (int argc, char* argv[]){

	FILE* fp;
	char arqName[50], temp[50];
	PROCESSO_T  aux;
	int idshm, id2shm;
	INFO_T *p2shm;
	PROCESSO_T *pshm,*paux;
	int i = 0;

	if(argc == 1){
		printf("Nenhum arquivo de entrada informado\n");
		exit(-1);
	}

	strcpy(arqName, argv[1]);

	fp = fopen(arqName, "r");
	if(fp == NULL){
		printf("Arquivo nao encontrado\n");
		exit(-1);
	}

	/*da um shmget na mem compartilhada*/	
	if ((idshm = shmget(90108094, NUM_TAB*sizeof(struct processo), IPC_CREAT|0x1ff)) < 0){
	    printf("erro na criacao da memoria compartilhada(idshm)\n");
	    exit(1);
	}

	/*da um attach na mem compartilhada*/
	pshm = (struct processo *) shmat(idshm, (char *)0, 0);
	if (pshm == (struct processo *)-1) {
        printf("erro no attach\n");
        exit(1);
    }

	/*da um shmget na mem compartilhada de bloqueio*/	
	if ((id2shm = shmget(90108012, sizeof(INFO_T), IPC_CREAT|0x1ff)) < 0){
	    printf("erro na criacao da memoria compartilhada(id2shm)\n");
	    exit(1);
	}

	/*da um attach na mem compartilhada de bloqueio para ver se pode escrever ou nao*/
	p2shm = (INFO_T *) shmat(id2shm, (char *)0, 0);
	if (p2shm == (INFO_T *)-1){
        printf("erro no attach\n");
        exit(1);
    }

	/*da um semget em semaforo para cria-lo*/
	if ((idsem = semget(90015266, 1, IPC_CREAT|0x1ff)) < 0){
	     printf("erro na criacao do semaforo\n");
	     exit(1);
	}


	getValue(&fp,aux.proc);/*pega o nome do programa*/
	getValue(&fp,aux.max_time);/*Pega o tempo m‡ximo de execucao*/
	getValue(&fp,temp);
	aux.num_proc = atoi(temp);/*Pega o numero de processos e transforma em inteiro*/
	aux.start_time = time(NULL);/*Pega o tempo de inicio da execucao*/
	aux.status = PENDING;


	/*printProcesso(aux);*/	

	p_sem();

		if(p2shm->write_permission != NAO_PODE_ESCREVER){
			i=0;

			paux = pshm;
			while(paux[i].nreq != 0 ){
				i++;
			}

			paux[i].nreq = ++p2shm->last_nreq;
			strcpy(paux[i].max_time,aux.max_time);
			paux[i].num_proc = aux.num_proc;
			paux[i].start_time = aux.start_time;
			paux[i].status = aux.status;
		   	strcpy(paux[i].proc,aux.proc); 
		   	paux[i].pid = 0;
		}else{
			printf("Gerenciador em processo de desligamneto\n");
		}


	v_sem();

	fclose(fp);
	return 0;
}
开发者ID:yclavinas,项目名称:trabalhoSO,代码行数:93,代码来源:so_submit.c


示例9: main

int main (int argc, char** argv)
{
//=============== CHECKING_MAIN_ARGS ========================================
    ASSERT_rcv (argc == 1,
                "ERROR: the program needs no arguments");

//=============== CREATING_SEMAPHORES_&_SOPS ================================
    ASSERT_rcv (creat ("key_file", 0644) != -1,
                "ERROR: creat (sem, key_file) failed");

    int semkey = ftok ("key_file", 2);
    ASSERT_rcv (semkey != -1,
                "ERROR: ftok (sem) failed");

    int semid = semget (semkey, NSEMS, IPC_CREAT | 0644);
	ASSERT_rcv (semid != -1,
                "ERROR: semget failed");

    struct sembuf sops[SOPS_SIZE];

//=============== TRYING_TO_START_WORK ======================================
    set_sop (sops, 0, SEM_RCV_CAN_START, 0, IPC_NOWAIT);
    set_sop (sops, 1, SEM_RCV_CAN_START, 1, 0);
    set_sop (sops, 2, SEM_RCV_ALIVE,     1, 0);
    set_sop (sops, 3, SEM_RCV_ALIVE,    -1, SEM_UNDO);

    if (semop   (semid, sops, 4) == -1) return 0;

//=============== CREATING_SHARED_MEMORY_&_ATTACHING ========================
    ASSERT_rcv (creat ("key_file", 0644) != -1,
                "ERROR: creat (shm, key_file) failed");

    int shmkey = ftok ("key_file", 1);
    ASSERT_rcv (shmkey != -1,
                "ERROR: ftok (shm) failed");

    int shmid = shmget (shmkey, BUF_SIZE + sizeof(int) + 1, IPC_CREAT | 0644);
	ASSERT_rcv (shmid != -1,
                "ERROR: shmget failed");

    void* shmptr = shmat (shmid, NULL, 0);

//================= SOME_PREPARATIONS =======================================
    /*void *buf = calloc (BUF_SIZE, 1);
    ASSERT_rcv (buf,
                "ERROR: calloc failed");*/

    set_sop (sops, 0, SEM_SND_MUTEX, 1, SEM_UNDO);
    set_sop (sops, 1, SEM_SND_MUTEX, -1, 0);
    set_sop (sops, 2, SEM_RCV_READY, 1, 0);
    set_sop (sops, 3, SEM_SND_READY, -1, 0);
    assert  (semop (semid, sops, 4) != -1);

//=============== GETTING_THE_FILE_FROM_SENDER ==============================
    /*set_sop (sops, 0, SEM_SND_READY, -1, 0);
    semop (semid, sops, 1);*/
    while (1) {
DEBUG   printf ("***");
DEBUG   sleep (1);
        set_sop (sops, 0, SEM_SND_ALIVE, 0, IPC_NOWAIT);
        smart_ASSERT_rcv (semop (semid, sops, 1) != -1,
                    "ERROR: Sender is dead");

        set_sop (sops, 0, SEM_RCV_MUTEX, 0, 0);// waiting for news from sender, if reciever can continue
        smart_ASSERT_rcv (semop (semid, sops, 1) != -1,
                    "ERROR: something went wrong while waiting for rcv_mutex == 0");

        set_sop (sops, 0, SEM_SUCCESS, -1, IPC_NOWAIT);
        if (semop (semid, sops, 1) == 0) break;
        printf ("%s", (char*) shmptr);

        set_sop (sops, 0, SEM_SND_MUTEX, -1, IPC_NOWAIT);
        set_sop (sops, 1, SEM_RCV_MUTEX,  1, 0);
        assert (semop (semid, sops, 2) != -1);
    }
//=============== FINISHING_WORK ============================================
    int nBytes = *((int*) &(shmptr[BUF_SIZE]));
    memset (shmptr + nBytes, 0, 1);
    printf ("%s", (char*) shmptr);

    shmdt  (shmptr);
    shmctl (shmid, IPC_RMID, 0);

    /*set_sop (sops, 0, SEM_RCV_READY, 1, 0); //Telling reciever, that sender is ready to finish
    semop (semid, sops, 1);
    set_sop (sops, 0, SEM_SND_READY, -1, 0);//Waiting for the moment, when reciever is ready to finish
    semop (semid, sops, 1);
    semctl (semid, IPC_RMID, 0);*/
    //free   (buf);

    return 0;
}
开发者ID:StrausMG,项目名称:learning,代码行数:92,代码来源:lrcv.c


示例10: main

int main(void)
{
    char	*cp=NULL;
    int	shmid, pid, status;
    key_t 	key;

    key = (key_t) getpid() ;

    /*---------------------------------------------------------*/

    errno = 0;

    if ((shmid = shmget(key, SIZE, IPC_CREAT|0666)) < 0) {
        perror("shmget");
        tst_resm(TFAIL,"Error: shmget: shmid = %d, errno = %d\n",
                 shmid, errno) ;
        tst_exit() ;
    }

#ifdef __ia64__
    cp = (char *) shmat(shmid, ADDR_IA, 0);
#elif defined(__ARM_ARCH_4T__)
    cp = (char *) shmat(shmid, (void *) NULL, 0);
#else
    cp = (char *) shmat(shmid, ADDR, 0);
#endif
    if (cp == (char *)-1) {
        perror("shmat");
        tst_resm(TFAIL,
                 "Error: shmat: shmid = %d, errno = %d\n",
                 shmid, errno) ;
        rm_shm(shmid) ;
        tst_exit() ;
    }

    *cp 	= '1';
    *(cp+1) = '2';

    tst_resm(TPASS,"shmget,shmat");

    /*-------------------------------------------------------*/


    pid = fork() ;
    switch (pid) {
    case -1 :
        tst_resm(TBROK,"fork failed");
        tst_exit() ;

    case 0  :
        if (*cp != '1') {
            tst_resm(TFAIL, "Error: not 1\n");
        }
        if (*(cp+1) != '2') {
            tst_resm(TFAIL, "Error: not 2\n");
        }
        tst_exit() ;
    }

    /* parent */
    while( wait(&status) < 0 && errno == EINTR ) ;

    tst_resm(TPASS,"cp & cp+1 correct") ;

    /*-----------------------------------------------------------*/
    rm_shm(shmid) ;
    tst_exit() ;
    /*-----------------------------------------------------------*/
    return(0);
}
开发者ID:mluszczyk,项目名称:so-minix,代码行数:70,代码来源:shmt07.c


示例11: ocs_sort

void ocs_sort(void *base, size_t nel, size_t width,
              int (*compar)(const void*, const void*),
              const char* caller)
{
    /* get a handle on libc caller sort function */
    void (*libc_sort)(void*, size_t, size_t, int (*)(const void*, const void*));
    dlerror(); /* At each call to dlerror(), the error indication is reset. */
    libc_sort = dlsym(RTLD_NEXT, caller);
    const char* error = dlerror();
    if (error)
    {
        /* something really really bad did happen ! */
        fprintf(stderr, "Could not find libc %s: %s\n", caller, error);
        exit(1);
    }

    /* allocate the corresponding Schwartzian array */
    ocs_schwartzian_array_t* schwartzian_array = ocs_schwartzian_array_new(base, nel, width);
    if (schwartzian_array == NULL)
    {
        /* unable to allocate memory, fall back to libc caller sorting function on base */
        libc_sort(base, nel, width, compar);
        return;
    }

    /* sort schwartzian array */
    ocs_schwartzian_array_sort(schwartzian_array, ocs_compar(compar));

    /* allocate a new permutation */
    ocs_permutation_t* permutation = ocs_permutation_new(nel);
    if (permutation == NULL)
    {
        /* unable to allocate memory, fall back to libc caller sorting function on base */
        ocs_schwartzian_array_destroy(schwartzian_array);
        libc_sort(base, nel, width, compar);
        return;
    }

    /* initialize the permutation from the sorted schwartzian array */
    ocs_schwartzian_array_to_permutation(schwartzian_array, permutation);

    /* */
    char *permutation_as_json_string = ocs_permutation_to_json_string(permutation);
    if (permutation_as_json_string == NULL)
    {
        /* unable to construct the associated JSON string, fall back to libc caller sorting function on base */
        ocs_permutation_destroy(permutation);
        ocs_schwartzian_array_destroy(schwartzian_array);
        libc_sort(base, nel, width, compar);
        return;
    }

    const int shared_segment_size = strlen(permutation_as_json_string) * sizeof(int);

    /* put the JSON string permutation in shared memory */
    key_t  shm_key;
    int    shm_id;
    size_t shm_size;

    shm_size = strlen(permutation_as_json_string);

    shm_id = shmget(IPC_PRIVATE, shm_size, 0644 | IPC_CREAT);

    /* Write the JSON string permutation to the shared memory segment.  */
    sprintf(shared_memory_segment, permutation_as_json_string);

    int *t;
    t = (int*) shmat(shm_id, 0, 0);
    for (int i = 0; i < nel; i++)
    {
        t[i] = permutation[i];
    }
    permutation[nel] = 0;

    /* */
    int queue_id = ocs_queue_get_id();


    ocs_queue_message_t message;
    message.type = OCS_QUEUE_MESSAGE_TYPE_PERMUTATION;
    message.func = OCS_QUEUE_MESSAGE_FUNC_QSORT;
    message.data = permutation;
    size_t message_length = OCS_QUEUE_MESSAGE_SIZE;

    if (msgsnd(queue_id, &message, mesage_length, IPC_NOWAIT) < 0)
    {
        printf ("%d, %d, %d, %s, %d\n", queue_id, message.type, message_func, buffer.text, buffer_length);
        perror("msgsnd");
        exit(1);
    }




    /* destroy OCS schwartzian array */
    ocs_schwartzian_array_destroy(schwartzian_array);

    /* done with the monitoring, call libc qsort function */
    libc_qsort(base, nel, width, compar);
}
开发者ID:vialette,项目名称:ocs-c,代码行数:100,代码来源:ocs_sort.c


示例12: main


//.........这里部分代码省略.........
	tPortSettings.c_iflag &= ~(IGNPAR|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
	/*tPortSettings.c_iflag |= (IXON|IXOFF);  // enable software flow control */
	tPortSettings.c_cflag &= ~(CSIZE|PARENB);
	/*tPortSettings.c_cflag |= (B115200|CS8|CLOCAL|CREAD); */
	tPortSettings.c_cflag |= (CS8|CLOCAL|CREAD);

	/* Set the Baud Rate (same for input and output) */
	cfsetispeed(&tPortSettings, iBaudRate);
	cfsetospeed(&tPortSettings, iBaudRate);

	tPortSettings.c_oflag &= ~(OPOST);
	tPortSettings.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
	tPortSettings.c_cc[VTIME] = 10; /* wait for 1 second before returning */
	tPortSettings.c_cc[VMIN] = 0;   /* can return with no data */
	tcflush(iPort,TCIFLUSH);
	tcsetattr(iPort,TCSANOW,&tPortSettings);

	
	/* connect to shared memory for GPS*/
	shmGPSKey = GPSDATA_KEY;
	if((shmGPSId = shmget(shmGPSKey, sizeof(GPSData), 0666)) < 0) 
	{
        	perror("shmget(): cannot find GPS data storage - no shared mem used");
       		iUseSharedMemory = 0;
    	} else
	{
		/* shared memory is intiialised */
		iUseSharedMemory = 1;
	}

	/* attach */
	if(iUseSharedMemory == 1)
	{
		if((ptGPSData = shmat(shmGPSId, NULL, 0)) == (GPSData *) -1) 
		{
			perror("shmat(): attaching GPS Data Storage");
			exit(-1);
		}
	} 

	log("Initialised GPS Store - Hit CTRL-C to exit");
	
	while(iShutdown == 0)
	{
		
		/* clear buffer */
		memset(azucBuffer,0,MAX_LOG_LENGTH);
		iAbandonPacket = 0;

		/* synchronoise packet - look for binary header - 0xAA 0x44 0x12 */
		do
		{
			azucBuffer[0] = azucBuffer[1];
			azucBuffer[1] = azucBuffer[2];
			iBytesRead = read(iPort,&azucBuffer[2],1);
			
			if(iShutdown == 1)
			{	
				iAbandonPacket=1;
				break;
			}
				
		} while(azucBuffer[0] != 0xAA && azucBuffer[1] != 0x44 && azucBuffer[2] != 0x12);
		
		if(iAbandonPacket == 1)
		{
开发者ID:duncang,项目名称:gpsins,代码行数:67,代码来源:gpsstore.c


示例13: CreerEtInitialiserFeux

pid_t CreerEtInitialiserFeux(int mtxFeux, int mColor, int mDuree)
// Mode d'emploi :
//	<mtxFeux> : Identifiant du tableau de sémaphore permettant la mise en place d'un mutex
//	<mColor> : L'identifiant de la mémoire partagée contenant la couleur des feux
//	<mDuree> : L'identifiant de la mémoire partagée contenant la durée
// Contrat :
//		- <mtxFeux> est un tableau de sémaphores de 2 cases, dont la première sert de mutex
//			à <mColor>, et la seconde à <mDuree>
//		- <mColor> est l'ID d'un mémoire partagée contenant 2 entiers
//		- <mDuree> est l'ID d'un mémoire partagée contenant 2 entiers
{
	pid_t pFeux;

	


	if((pFeux = fork()) == 0)
	{
		/** structures pour les opérations sur la durée (lecture) */
		struct sembuf getDLock;
		getDLock.sem_num = dureesLoc;
		getDLock.sem_op = 1;
		getDLock.sem_flg = 0;

		struct sembuf releaseDLock;
		releaseDLock.sem_num = dureesLoc;
		releaseDLock.sem_op = -1;
		releaseDLock.sem_flg = 0;


		/** structures pour les opérations sur la couleur (écriture) */
		struct sembuf getCLock;
		getCLock.sem_num = colorsLoc;
		getCLock.sem_op = 4;
		getCLock.sem_flg = 0;


		struct sembuf releaseCLock;
		releaseCLock.sem_num = colorsLoc;
		releaseCLock.sem_op = -4;
		releaseCLock.sem_flg = 0;

		/** Initialisation des variables locales */
		int tempsNS = 0;
		int tempsEO = 0;
		Colors couleurNS = ROUGE;
		Colors couleurEO = ROUGE;
		bool lastNS = false; // booléen permettant de savoir qui doit passer au vert

		couleursFeux = (couleurs*)shmat(mColor, NULL, 0);
		dureesFeux = (durees*)shmat(mDuree, NULL, 0);
		
		
		/** Mappage des signaux */
		struct sigaction action;
		action.sa_handler = handleEnd;
		sigemptyset(&action.sa_mask);
		action.sa_flags = 0;

		sigaction(SIGUSR2, &action, NULL);


		for(;;)
		{
			/** Gestion de l'axe NS */
			if(tempsNS <= 0)
			{
				switch (couleurNS)
				{
					case ROUGE:
						if(!lastNS)
						{
							couleurNS = VERT;
							lastNS = !lastNS;

							/** Récupération des durées, avec mutex */
							semop(mtxFeux, &getDLock, 1);

							tempsNS = dureesFeux->dureeNS;
							tempsEO = dureesFeux->dureeEO;

							semop(mtxFeux, &releaseDLock, 1);

							Afficher(DUREE_AXE_NS, tempsNS);
							Afficher(DUREE_AXE_EO, tempsEO);

							tempsEO = tempsNS + 5;
						}

						break;
					case VERT:
						couleurNS = ORANGE;
						tempsNS = 3;
						break;
					case ORANGE:
						couleurNS = ROUGE;
						tempsNS = 2;
						break;
				}
			}
//.........这里部分代码省略.........
开发者ID:robinroyer,项目名称:traffic-intersection-analysis,代码行数:101,代码来源:Feux.cpp


示例14: main

int main(int argc, char *argv[])
{
	int lc, fd;
	int i;
	char *file = NULL;
	struct stat stat;
	void *addr1;
	long shm_size = 0;

	char *msg = NULL;
	char filename[64];
	char *progname = NULL;
	char *str_for_file = "abcdefghijklmnopqrstuvwxyz12345\n";

	msg = parse_opts(argc, argv, NULL, NULL);
	if (msg)
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);

	setup();

	progname = *argv;
	sprintf(filename, "%s-out.%d", progname, getpid());

	for (lc = 0; TEST_LOOPING(lc); lc++) {
		Tst_count = 0;

		fd = open(filename, O_RDWR | O_CREAT, 0664);
		if (fd < 0)
			tst_brkm(TBROK, cleanup, "open failed");
#ifdef MM_DEBUG
		tst_resm(TINFO, "filename = %s opened successfully", filename);
#endif

		/* Writing 40 KB of random data into this file
		   [32 * 1280 = 40960] */
		for (i = 0; i < 1280; i++)
			if (write(fd, str_for_file, strlen(str_for_file)) == -1)
				tst_brkm(TBROK|TERRNO, cleanup, "write failed");

		if (fstat(fd, &stat) == -1)
			tst_brkm(TBROK, cleanup, "fstat failed");

		file = mmap(NULL, stat.st_size, PROT_READ, MAP_SHARED, fd, 0);
		if (file == MAP_FAILED)
			tst_brkm(TBROK|TERRNO, cleanup, "mmap failed");

		/* Allocate shared memory segment */
		shm_size = get_shmmax();

#define min(a, b) ((a) < (b) ? (a) : (b))
		shmid1 = shmget(IPC_PRIVATE, min(1024*1024, shm_size),
				IPC_CREAT|IPC_EXCL|0701);
		if (shmid1 == -1)
			tst_brkm(TBROK, cleanup, "shmget failed");

		/* Attach shared memory segment to an address selected by the system */
		addr1 = shmat(shmid1, NULL, 0);
		if (addr1 == (void *) -1)
			tst_brkm(TBROK, cleanup, "shmat error");

		/* (1) Test case for MADV_REMOVE */
		TEST(madvise(addr1, 4096, MADV_REMOVE));
		check_and_print("MADV_REMOVE");

		/* (2) Test case for MADV_DONTFORK */
		TEST(madvise(file, (stat.st_size / 2), MADV_DONTFORK));
		check_and_print("MADV_DONTFORK");

		/* (3) Test case for MADV_DOFORK */
		TEST(madvise(file, (stat.st_size / 2), MADV_DOFORK));
		check_and_print("MADV_DOFORK");

		/* Finally Unmapping the whole file */
		if (munmap(file, stat.st_size) < 0)
			tst_brkm(TBROK|TERRNO, cleanup, "munmap failed");

		close(fd);
	}

	cleanup();
	tst_exit();
}
开发者ID:Mellanox,项目名称:arc_ltp,代码行数:82,代码来源:madvise03.c


示例15: alloc_shared_mem

int alloc_shared_mem(int resume)
{
	int size = count_mem_used();
	int shmid;
	if (resume)
		shmid = shmget(key, size, 0666);
	else
		shmid = shmget(key, size, IPC_CREAT|IPC_EXCL|0666);
	if (shmid < 0) {
		log4c_category_log(mycat, LOG4C_PRIORITY_ERROR, "%s %d: shmget fail[%d]", __FUNCTION__, __LINE__, errno);		
		return (-1);
	}
	
	void *mem = shmat(shmid, NULL, 0);
	if (!mem) {
		log4c_category_log(mycat, LOG4C_PRIORITY_ERROR, "%s %d: shmat fail[%d]", __FUNCTION__, __LINE__, errno);		
		return (-10);
	}
	int offset = 0;
	pool_container_used = mem + offset;
	offset += sizeof(*pool_container_used);
	
	pool_container_freed = mem + offset;
	offset += sizeof(*pool_container_freed);
	
	pool_container = mem + offset;
	offset += sizeof(CONTAINER) * max_container_in_game;

	pool_thing_obj_used = mem + offset;
	offset += sizeof(*pool_thing_obj_used);

	pool_thing_obj_freed = mem + offset;
	offset += sizeof(*pool_thing_obj_freed);

	pool_thing_obj = mem + offset;
	offset += sizeof(THING_OBJ) * max_thing_obj_in_game;

	pool_role_used = mem + offset;
	offset += sizeof(*pool_role_used);

	pool_role_freed = mem + offset;
	offset += sizeof(*pool_role_freed);

	pool_role = mem + offset;
	offset += sizeof(ROLE) * max_role_in_game;

	pool_scene_used = mem + offset;
	offset += sizeof(*pool_scene_used);

	pool_scene_freed = mem + offset;
	offset += sizeof(*pool_scene_freed);

	pool_scene = mem + offset;
	offset += sizeof(SCENE) * max_scene_in_game;		

	pool_instance_used = mem + offset;
	offset += sizeof(*pool_instance_used);

	pool_instance_freed = mem + offset;
	offset += sizeof(*pool_instance_freed);

	pool_instance = mem + offset;
	offset += sizeof(INSTANCE) * max_instance_in_game;

	return (0);
}
开发者ID:a1406,项目名称:txgg,代码行数:66,代码来源:game_srv.c


示例16: x11_reset

static int x11_reset(struct vidisp_st *st, const struct vidsz *sz)
{
	XWindowAttributes attrs;
	XGCValues gcv;
	size_t bufsz, pixsz;
	int err = 0;

	if (!XGetWindowAttributes(st->disp, st->win, &attrs)) {
		warning("x11: cant't get window attributes\n");
		return EINVAL;
	}

	switch (attrs.depth) {

	case 24:
		st->pixfmt = VID_FMT_RGB32;
		pixsz = 4;
		break;

	case 16:
		st->pixfmt = VID_FMT_RGB565;
		pixsz = 2;
		break;

	case 15:
		st->pixfmt = VID_FMT_RGB555;
		pixsz = 2;
		break;

	default:
		warning("x11: colordepth not supported: %d\n", attrs.depth);
		return ENOSYS;
	}

	bufsz = sz->w * sz->h * pixsz;

	if (st->image) {
		XDestroyImage(st->image);
		st->image = NULL;
	}

	if (st->xshmat)
		XShmDetach(st->disp, &st->shm);

	if (st->shm.shmaddr != (char *)-1)
		shmdt(st->shm.shmaddr);

	if (st->shm.shmid >= 0)
		shmctl(st->shm.shmid, IPC_RMID, NULL);

	st->shm.shmid = shmget(IPC_PRIVATE, bufsz, IPC_CREAT | 0777);
	if (st->shm.shmid < 0) {
		warning("x11: failed to allocate shared memory\n");
		return ENOMEM;
	}

	st->shm.shmaddr = shmat(st->shm.shmid, NULL, 0);
	if (st->shm.shmaddr == (char *)-1) {
		warning("x11: failed to attach to shared memory\n");
		return ENOMEM;
	}

	st->shm.readOnly = true;

	x11.shm_error = 0;
	x11.errorh = XSetErrorHandler(error_handler);

	if (!XShmAttach(st->disp, &st->shm)) {
		warning("x11: failed to attach X to shared memory\n");
		return ENOMEM;
	}

	XSync(st->disp, False);
	XSetErrorHandler(x11.errorh);

	if (x11.shm_error)
		info("x11: shared memory disabled\n");
	else
		st->xshmat = true;

	gcv.graphics_exposures = false;

	st->gc = XCreateGC(st->disp, st->win, GCGraphicsExposures, &gcv);
	if (!st->gc) {
		warning("x11: failed to create graphics context\n");
		return ENOMEM;
	}

	if (st->xshmat) {
		st->image = XShmCreateImage(st->disp, attrs.visual,
					    attrs.depth, ZPixmap,
					    st->shm.shmaddr, &st->shm,
					    sz->w, sz->h);
	}
	else {
		st->image = XCreateImage(st->disp, attrs.visual,
					 attrs.depth, ZPixmap, 0,
					 st->shm.shmaddr,
					 sz->w, sz->h, 32, 0);

//.........这里部分代码省略.........
开发者ID:aKlausKranz,项目名称:baresip,代码行数:101,代码来源:x11.c


示例17: main

int main(int argc, char* argv[]){
	int j;
	int ncrits = 0; //number of times CS has been entered
	pn = atoi(argv[1]);
	int n = 20; //number of processes + 1
	pnc = argv[1];
	srand((unsigned)(time(NULL) + pn)); //initialize srand

	//mount shared memory
	int shmid = shmget(SHMKEY, BUFF_SZ, 0777);
	if(shmid == -1){
		perror("Slave: Error in shmget.");
		exit(1);
	}
	paddr = (char*)(shmat(shmid, 0, 0));
	pt * m = (pt*)(paddr);

	//setup signal handlers (ignore SIGINT that will be intercepted by master)
	signal(SIGQUIT, sigtimeout_handler);
	signal(SIGTERM, sigctlc_handler);
	signal(SIGINT, SIG_IGN);

	do{
		do{
			//declare intent to enter CS
			m->flag[pn] = want_in;
			j = m->turn;

			while(j != pn){
				j = (m->flag[j] != idle) ? (m->turn) : ((j + 1) % n);
			}

			//pmsg(pnc, "attempting to enter CS");
			m->flag[pn] = in_cs;

			//try to gain entry to CS
			for(j = 0; j < n; j++){
				if((j != pn) && (m->flag[j] == in_cs)){
					pmsg(pnc, "Failed to enter CS");
					break;
				}
			}

		}while((j < n) || ((m->turn != pn) && (m->flag[(m->turn)] != idle)));

		//critical section entry gained
		m->turn = pn;
		ncrits++;
		critical_section();
		pmsg(pnc, "out of CS");

		//search for next in line non-idle process
		j = (m->turn + 1) % n;
		while(m->flag[j] == idle){
			j = (j + 1) % n;
		}

		//set turn to next process, change flag to idle
		m->turn = j;
		m->flag[pn] = idle;
		sleep((rand() % 3));
	}while(ncrits < 3);

	//dismount memory and print finished message
	shmdt(paddr);
	pmsg(pnc, "done and detached");
	return 0;
}
开发者ID:BenHaase,项目名称:Concurrent-Processes-,代码行数:68,代码来源:slave.c


示例18: main

int main()
{
    int i,j;
    char buf0[20];
    char buf2[20];
    char buf3[20];
    char buf1[20];
    char buf4[20];
    char buf5[80];
    char buf6[80];
    
    char *bufargs[8] = {buf0,buf1,buf2,buf3,buf4,buf5,buf6,(char*)0};/* arrays which will store the arguments that will be passed to ./multiply*/
                                                                    /*Requires the NULL value at the end!*/
    int *matrix;
    int id_shmem, counter =0, mypid =0,pid, status;
    int inputmatrix1[20][20];
    int inputmatrix2[20][20];
    int rows; // The number of rows of the 2D array
    int columns=0;// The number of columns of the 2D array
    int rows2, columns2; //Size of 2nd 2D array
    readmats(inputmatrix1, inputmatrix2, &rows, &columns, &rows2, &columns2);

    //Allocates correct amount of memory to hold the final matrix
    if((id_shmem = shmget(IPC_PRIVATE, sizeof(int)*rows*columns2, IPC_CREAT|0666)) < 0)
        err_sys("shmget error");

   

鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C++ shmctl函数代码示例发布时间:2022-05-30
下一篇:
C++ shm_unlock函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap