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; }
/* 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; }
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; }
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(); in = buf_init(); /* Get command line input */ printf("> "); while((c = getchar()) != EOF) { buf_addc(&in, c); if(c == '\n') { buf_addc(&in, '\0'); parse(in->buf); process_tasks(); buf_reset(&in); printf("> "); } } buf_free(in); pthread_mutex_lock(&station_table_lock); /* kill all children */ for(c = 0; c < SYM_TABLE_SIZE; c++) { rec = station_table.table[c]; while(rec) { kill_child(rec->data.ptr); recb = rec->next; free(rec); rec = recb; } } pthread_mutex_unlock(&station_table_lock); pthread_mutex_destroy(&station_table_lock); fclose(logfile); exit(EXIT_SUCCESS); }
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; }
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; }
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; }
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; }
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; }
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); }
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); }
int main(int argc, char *argv[]) { char *azcPort = "/dev/ttyS0"; char *azcBaud = "230400"; int iBaudRate = 230400; int iPort; int iBytesRead = 0; unsigned char azucBuffer[MAX_LOG_LENGTH]; unsigned char ucHeaderLength = 0; int iTotalBytes = 0; unsigned short usMessageLength = 0; unsigned short usMessageID = 0; unsigned long ulCRC_Calc, ulCRC_Tx; /** controls if shared memory is open for use: 0 - No, 1 - Yes */ int iUseSharedMemory = 0; struct termios tPortSettings; /** structure to store positions */ BESTPOS BestPosData; RANGE RangeData; GPSEPHEM GPSEphemeris[MAX_PRNS]; int iAbandonPacket = 0; long lMeasurementNumber = 0; GPSTime GPSTimeStamp; unsigned long ulGPSMilliSeconds; unsigned long ulPRN; /* shared memory objects */ int shmGPSId; key_t shmGPSKey; /* GPS Data reference */ GPSData *ptGPSData; /* setup signal handlers */ signal(SIGHUP, HandleSignal); signal(SIGKILL, HandleSignal); signal(SIGTERM, HandleSignal); signal(SIGALRM, HandleSignal); signal(SIGINT, HandleSignal); /* read input parameters */ switch(argc) { case 1: /* defaults */ break; case 2: /* set port */ azcPort = argv[1]; break; case 3: /* set port and baud */ azcPort = argv[1]; azcBaud = argv[2]; switch(atoi(azcBaud)) { case 9600: iBaudRate = B9600; break; case 19200: iBaudRate = B19200; break; case 38400: iBaudRate = B38400; break; case 57600: iBaudRate = B57600; break; case 115200: iBaudRate = B115200; break; case 230400: iBaudRate = B230400; break; default: fprintf(stderr,"Unknown Baud - setting default B230400!\n"); iBaudRate = B230400; break; } break; default: fprintf(stderr,"%s Unknown Argument List... Exiting\n",MODULE_NAME); exit(-1); break; } fprintf(stdout,"%s Using Port: %s at %s\n",MODULE_NAME, azcPort, azcBaud); /* open port */ iPort = open(azcPort, O_RDWR); if(iPort < 0) { fprintf(stderr,"Cannot open port, %s:",azcPort); perror("open()"); exit(-1); } /* initialise port settings */ bzero(&tPortSettings,sizeof(tPortSettings)); /* configure port settings */ 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) { continue; } /* read header length */ iBytesRead = read(iPort,&azucBuffer[3],1); if(iBytesRead == 1) { ucHeaderLength = azucBuffer[3]; } else { log("Could not read header length"); break; } /* sanity check on header length */ if(ucHeaderLength > 28) { /* too large - try again */ err("Header unexpectedly large"); iAbandonPacket = 1; continue; } /* we have already received the first 4 bytes */ iTotalBytes = 4; /* read rest of header */ while(iTotalBytes<ucHeaderLength) { iBytesRead = read(iPort,&azucBuffer[iTotalBytes],MAX_LOG_LENGTH-2); iTotalBytes += iBytesRead; if(iTotalBytes > MAX_LOG_LENGTH) { err("Too many bytes received"); iAbandonPacket = 1; break; } } if(iAbandonPacket == 1) { continue; } /* read message length */ memcpy(&usMessageLength,&azucBuffer[8],2); /* receive rest of message */ while(iTotalBytes<(ucHeaderLength + usMessageLength + 4)) /* 4 is the length of the CRC */ { iBytesRead = read(iPort,&azucBuffer[iTotalBytes],MAX_LOG_LENGTH-2); iTotalBytes += iBytesRead; if(iTotalBytes > MAX_LOG_LENGTH) { err("Too many bytes received"); iAbandonPacket = 1; break; } } if(iAbandonPacket == 1) { continue; } /* get the message ID */ memcpy(&usMessageID,&azucBuffer[4],2); /* debug message */ fprintf(stdout,"Message type: %d received, %d bytes total\n",usMessageID, iTotalBytes); /* perform checksum */ ulCRC_Calc = CalculateBlockCRC32(ucHeaderLength+usMessageLength,azucBuffer); /* retrieve checksum from message */ memcpy(&ulCRC_Tx,&azucBuffer[ucHeaderLength+usMessageLength],4); if(ulCRC_Tx != ulCRC_Calc) { /* we have an error */ log("CRC Check Error"); } else { /* get the time stamp */ memcpy(&GPSTimeStamp.usGPSWeek,&azucBuffer[14],2); memcpy(&ulGPSMilliSeconds,&azucBuffer[16],4); GPSTimeStamp.fGPSSecondOfWeek = ((float)ulGPSMilliSeconds) / 1000.0; /* extract the message data */ switch(usMessageID) { case NOVATEL_BESTPOS: /* copy timestamp */ memcpy(&BestPosData.gtTimeStamp,&GPSTimeStamp,sizeof(GPSTime)); /*extract data */ memcpy(&BestPosData.dLatitude,&azucBuffer[ucHeaderLength+8],8); memcpy(&BestPosData.dLongitude,&azucBuffer[ucHeaderLength+16],8); memcpy(&BestPosData.dHeight,&azucBuffer[ucHeaderLength+24],8); memcpy(&BestPosData.fUndulation,&azucBuffer[ucHeaderLength+32],4); memcpy(&BestPosData.ulDatumID,&azucBuffer[ucHeaderLength+36],4); memcpy(&BestPosData.fLatitudeSigma,&azucBuffer[ucHeaderLength+40],4); memcpy(&BestPosData.fLongitudeSigma,&azucBuffer[ucHeaderLength+44],4); memcpy(&BestPosData.fHeightSigma,&azucBuffer[ucHeaderLength+48],4); memcpy(&BestPosData.azucBaseStationID[0],&azucBuffer[ucHeaderLength+52],4); memcpy(&BestPosData.fDifferentialAge,&azucBuffer[ucHeaderLength+56],4); memcpy(&BestPosData.fSolutionAge,&azucBuffer[ucHeaderLength+60],4); memcpy(&BestPosData.ucNumberObservationsTracked,&azucBuffer[ucHeaderLength+64],1); memcpy(&BestPosData.ucNumberL1ObservationsUsed,&azucBuffer[ucHeaderLength+65],1); memcpy(&BestPosData.ucNumberL1ObservationsAboveRTKMaskAngle,&azucBuffer[ucHeaderLength+66],1); memcpy(&BestPosData.ucNumberL2ObservationsAboveRTKMaskAngle,&azucBuffer[ucHeaderLength+67],1); fprintf(stdout,"BESTPOS: %lf %lf %lf\n",BestPosData.dLatitude, BestPosData.dLongitude, BestPosData.dHeight); break; case NOVATEL_RANGE: /* pseudorange measurements */ /* copy timestamp */ memcpy(&RangeData.gtTimeStamp,&GPSTimeStamp,sizeof(GPSTime)); /* get number of measurements */ memcpy(&RangeData.lNumberObservations,&azucBuffer[ucHeaderLength],4); fprintf(stdout,"RANGE: %ld Measurements\n",RangeData.lNumberObservations); /* limit max measurements */ if(RangeData.lNumberObservations > NOVATEL_MAXCHANNELS) { RangeData.lNumberObservations = NOVATEL_MAXCHANNELS; } for(lMeasurementNumber=0;lMeasurementNumber<RangeData.lNumberObservations;lMeasurementNumber++) { memcpy(&RangeData.usPRN[lMeasurementNumber], &azucBuffer[ucHeaderLength + 4 + lMeasurementNumber*44],2); memcpy(&RangeData.usGlonassFrequency[lMeasurementNumber], &azucBuffer[ucHeaderLength + 6 + lMeasurementNumber*44],2); memcpy(&RangeData.dPseudorange[lMeasurementNumber], &azucBuffer[ucHeaderLength + 8 + lMeasurementNumber*44],8); memcpy(&RangeData.fPseudorangeSigma[lMeasurementNumber], &azucBuffer[ucHeaderLength + 16 + lMeasurementNumber*44],4); memcpy(&RangeData.dCarrierPhase[lMeasurementNumber], &azucBuffer[ucHeaderLength + 20 + lMeasurementNumber*44],8); memcpy(&RangeData.fCarrierPhaseSigma[lMeasurementNumber], &azucBuffer[ucHeaderLength + 28 + lMeasurementNumber*44],4); memcpy(&RangeData.fDoppler[lMeasurementNumber], &azucBuffer[ucHeaderLength + 32 + lMeasurementNumber*44],4); memcpy(&RangeData.fCNo[lMeasurementNumber], &azucBuffer[ucHeaderLength + 36 + lMeasurementNumber*44],4); memcpy(&RangeData.fLockTime[lMeasurementNumber], &azucBuffer[ucHeaderLength + 40 + lMeasurementNumber*44],4); memcpy(&RangeData.ulTrackingStatus[lMeasurementNumber], &azucBuffer[ucHeaderLength + 44 + lMeasurementNumber*44],4); /* fprintf(stdout,"%d %f: RANGE: PRN:%d %lf\n", RangeData.gtTimeStamp.usGPSWeek, RangeData.gtTimeStamp.fGPSSecondOfWeek, RangeData.usPRN[lMeasurementNumber], RangeData.dPseudorange[lMeasurementNumber]); */ } break; case NOVATEL_GPSEPHEM: /* satellite ephemeris */ /* get the PRN */ memcpy(&ulPRN,&azucBuffer[ucHeaderLength],4); /* copy timestamp */ memcpy(&GPSEphemeris[ulPRN].gtTimeStamp,&GPSTimeStamp,sizeof(GPSTime)); /* copy ephemeris parameters */ memcpy(&GPSEphemeris[ulPRN].ulPRN,&azucBuffer[ucHeaderLength],4); memcpy(&GPSEphemeris[ulPRN].dTOW,&azucBuffer[ucHeaderLength+4],8); memcpy(&GPSEphemeris[ulPRN].ulHealth,&azucBuffer[ucHeaderLength+12],4); memcpy(&GPSEphemeris[ulPRN].ulIODE1,&azucBuffer[ucHeaderLength+16],4); memcpy(&GPSEphemeris[ulPRN].ulIODE2,&azucBuffer[ucHeaderLength+20],4); memcpy(&GPSEphemeris[ulPRN].ulGPSWeek,&azucBuffer[ucHeaderLength+24],4); memcpy(&GPSEphemeris[ulPRN].ulZWeek,&azucBuffer[ucHeaderLength+28],4); memcpy(&GPSEphemeris[ulPRN].dTOE,&azucBuffer[ucHeaderLength+32],8); memcpy(&GPSEphemeris[ulPRN].dA,&azucBuffer[ucHeaderLength+40],8); memcpy(&GPSEphemeris[ulPRN].dDeltaN,&azucBuffer[ucHeaderLength+48],8); memcpy(&GPSEphemeris[ulPRN].dM0,&azucBuffer[ucHeaderLength+56],8); memcpy(&GPSEphemeris[ulPRN].dEccentricity,&azucBuffer[ucHeaderLength+64],8); memcpy(&GPSEphemeris[ulPRN].dOmega,&azucBuffer[ucHeaderLength+72],8); memcpy(&GPSEphemeris[ulPRN].dcuc,&azucBuffer[ucHeaderLength+80],8); memcpy(&GPSEphemeris[ulPRN].dcus,&azucBuffer[ucHeaderLength+88],8); memcpy(&GPSEphemeris[ulPRN].dcrc,&azucBuffer[ucHeaderLength+96],8); memcpy(&GPSEphemeris[ulPRN].dcrs,&azucBuffer[ucHeaderLength+104],8); memcpy(&GPSEphemeris[ulPRN].dcic,&azucBuffer[ucHeaderLength+112],8); memcpy(&GPSEphemeris[ulPRN].dcis,&azucBuffer[ucHeaderLength+120],8); memcpy(&GPSEphemeris[ulPRN].dInclination0,&azucBuffer[ucHeaderLength+128],8); memcpy(&GPSEphemeris[ulPRN].dInclination_dot,&azucBuffer[ucHeaderLength+136],8); memcpy(&GPSEphemeris[ulPRN].dOmega0,&azucBuffer[ucHeaderLength+144],8); memcpy(&GPSEphemeris[ulPRN].dOmega_dot,&azucBuffer[ucHeaderLength+152],8); memcpy(&GPSEphemeris[ulPRN].ulIODC,&azucBuffer[ucHeaderLength+160],4); memcpy(&GPSEphemeris[ulPRN].dTOC,&azucBuffer[ucHeaderLength+164],8); memcpy(&GPSEphemeris[ulPRN].dTGD,&azucBuffer[ucHeaderLength+172],8); memcpy(&GPSEphemeris[ulPRN].dA_f0,&azucBuffer[ucHeaderLength+180],8); memcpy(&GPSEphemeris[ulPRN].dA_f1,&azucBuffer[ucHeaderLength+188],8); memcpy(&GPSEphemeris[ulPRN].dA_f2,&azucBuffer[ucHeaderLength+196],8); memcpy(&GPSEphemeris[ulPRN].ulAntiSpoofing,&azucBuffer[ucHeaderLength+204],4); memcpy(&GPSEphemeris[ulPRN].dN,&azucBuffer[ucHeaderLength+208],8); memcpy(&GPSEphemeris[ulPRN].dURA,&azucBuffer[ucHeaderLength+216],8); fprintf(stdout,"PRN%ld Ephemeris Stored\n",GPSEphemeris[ulPRN].ulPRN); break; default: log("Unknown Message"); break; } } } /* shutdown */ close(iPort); log("Shutting Down"); /* exit */ return 0; } /* main */
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; } } /** Gestion de l'axe EO */ if(tempsEO <= 0) { switch (couleurEO) { case ROUGE: if(lastNS) { couleurEO = 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); tempsNS = tempsEO + 5; } break; case VERT: couleurEO = ORANGE; tempsNS = 3; break; case ORANGE: couleurEO = ROUGE; tempsNS = 2; break; } } Afficher(TEMPS_AXE_NS, tempsNS); Afficher(TEMPS_AXE_EO, tempsEO); couleurFeu(COULEUR_AXE_NS, couleurNS); couleurFeu(COULEUR_AXE_EO, couleurEO); /** Ecriture des couleurs des feux, avec mutex */ semop(mtxFeux, &getCLock, 1); couleursFeux->colNS = couleurNS; couleursFeux->colEO = couleurEO; semop(mtxFeux, &releaseCLock, 1); tempsNS--; tempsEO--; sleep(1); } } else { return pFeux; } } //----- fin de CreerEtInitialiserFeux
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(); }
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); }
void runSuccess1() { shmat(anyint(), NULL, anyint()); }
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); } if (!st->image) { warning("x11: Failed to create X image\n"); return ENOMEM; } XResizeWindow(st->disp, st->win, sz->w, sz->h); st->size = *sz; return err; }
void runSuccess() { shmat(anyint(), anyptr(), anyint()); }
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; }
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"); if((matrix = (int *)shmat(id_shmem, 0, 0)) == NULL) err_sys("shmat error"); int row, column; for (row = 0; row < rows; row++){ for (column = 0; column < columns2; column++){ if ((mypid = fork()) < 0) { err_sys("fork error"); } else if (mypid == 0) { /*Child*/ snprintf(bufargs[2],20,"%d",columns2); /*maximum number of columns in final matrix*/ snprintf(bufargs[1],20,"%d",row); /*Row number where result will be place*/ snprintf(bufargs[3],20,"%d",column); /*Column number where result will be placed*/ snprintf(bufargs[0],20,"%d",id_shmem); /*ID of shared memory object*/ int ptr = 0; for(i = 0; i < columns; i++) { ptr += snprintf(bufargs[4] + ptr,sizeof(bufargs[4]),"%d ", inputmatrix1[row][i]); //Creation of string that will hold the row of the first matrix } ptr = 0; for(i = 0; i < columns; i++) { ptr += snprintf(bufargs[5] + ptr, sizeof(bufargs[5]), "%d ", inputmatrix2[i][column]); //Creation of string that will hold the column of the second matrix } counter++; if(execvp("./multiply",bufargs) ) { perror("Cannot 'exec', make sure correct pathname for multiply is specified\n"); exit(1); } else{ } } } } /*Parent*/ if(mypid >0) { while ((pid = wait(&status)) > 0) { } //printf("All done! %d\n",counter); for (i = 0; i < rows; i++) { for (j = 0; j < columns2; j++) { if(j == columns2-1){ printf("%d", matrix[i*columns2 + j]); fflush(stdout); } else{ printf("%d ", matrix[i*columns2 + j]); fflush(stdout); } } printf("\n"); fflush(stdout); } } shmdt(matrix); shmctl(id_shmem, IPC_RMID, 0); return(4); }
SDL_Overlay *X11_CreateYUVOverlay(_THIS, int width, int height, Uint32 format, SDL_Surface *display) { SDL_Overlay *overlay; struct private_yuvhwdata *hwdata; int xv_port; unsigned int i, j, k; unsigned int adaptors; SDL_NAME(XvAdaptorInfo) *ainfo; int bpp; #ifndef NO_SHARED_MEMORY XShmSegmentInfo *yuvshm; #endif /* Look for the XVideo extension with a valid port for this format */ xv_port = -1; if ( (Success == SDL_NAME(XvQueryExtension)(GFX_Display, &j, &j, &j, &j, &j)) && (Success == SDL_NAME(XvQueryAdaptors)(GFX_Display, RootWindow(GFX_Display, SDL_Screen), &adaptors, &ainfo)) ) { #ifdef USE_LAST_ADAPTOR for ( i=0; i < adaptors; ++i ) #else for ( i=0; (i < adaptors) && (xv_port == -1); ++i ) #endif /* USE_LAST_ADAPTOR */ { /* Check to see if the visual can be used */ if ( BUGGY_XFREE86(<=, 4001) ) { int visual_ok = 0; for ( j=0; j<ainfo[i].num_formats; ++j ) { if ( ainfo[i].formats[j].visual_id == SDL_Visual->visualid ) { visual_ok = 1; break; } } if ( ! visual_ok ) { continue; } } if ( (ainfo[i].type & XvInputMask) && (ainfo[i].type & XvImageMask) ) { int num_formats; SDL_NAME(XvImageFormatValues) *formats; formats = SDL_NAME(XvListImageFormats)(GFX_Display, ainfo[i].base_id, &num_formats); #ifdef USE_LAST_ADAPTOR for ( j=0; j < num_formats; ++j ) #else for ( j=0; (j < num_formats) && (xv_port == -1); ++j ) #endif /* USE_LAST_ADAPTOR */ { if ( (Uint32)formats[j].id == format ) { for ( k=0; k < ainfo[i].num_ports; ++k ) { if ( Success == SDL_NAME(XvGrabPort)(GFX_Display, ainfo[i].base_id+k, CurrentTime) ) { xv_port = ainfo[i].base_id+k; break; } } } } if ( formats ) { XFree(formats); } } } SDL_NAME(XvFreeAdaptorInfo)(ainfo); } /* Precalculate the bpp for the pitch workaround below */ switch (format) { /* Add any other cases we need to support... */ case SDL_YUY2_OVERLAY: case SDL_UYVY_OVERLAY: case SDL_YVYU_OVERLAY: bpp = 2; break; default: bpp = 1; break; } #if 0 /* * !!! FIXME: * "Here are some diffs for X11 and yuv. Note that the last part 2nd * diff should probably be a new call to XvQueryAdaptorFree with ainfo * and the number of adaptors, instead of the loop through like I did." * * ACHTUNG: This is broken! It looks like XvFreeAdaptorInfo does this * for you, so we end up with a double-free. I need to look at this * more closely... --ryan. */ for ( i=0; i < adaptors; ++i ) { if (ainfo[i].name != NULL) Xfree(ainfo[i].name); if (ainfo[i].formats != NULL) Xfree(ainfo[i].formats); } Xfree(ainfo); #endif if ( xv_port == -1 ) { SDL_SetError("No available video ports for requested format"); return(NULL); } /* Enable auto-painting of the overlay colorkey */ { static const char *attr[] = { "XV_AUTOPAINT_COLORKEY", "XV_AUTOPAINT_COLOURKEY" }; unsigned int i; SDL_NAME(XvSelectPortNotify)(GFX_Display, xv_port, True); X_handler = XSetErrorHandler(xv_errhandler); for ( i=0; i < sizeof(attr)/(sizeof attr[0]); ++i ) { Atom a; xv_error = False; a = XInternAtom(GFX_Display, attr[i], True); if ( a != None ) { SDL_NAME(XvSetPortAttribute)(GFX_Display, xv_port, a, 1); XSync(GFX_Display, True); if ( ! xv_error ) { break; } } } XSetErrorHandler(X_handler); SDL_NAME(XvSelectPortNotify)(GFX_Display, xv_port, False); } /* Create the overlay structure */ overlay = (SDL_Overlay *)SDL_malloc(sizeof *overlay); if ( overlay == NULL ) { SDL_NAME(XvUngrabPort)(GFX_Display, xv_port, CurrentTime); SDL_OutOfMemory(); return(NULL); } SDL_memset(overlay, 0, (sizeof *overlay)); /* Fill in the basic members */ overlay->format = format; overlay->w = width; overlay->h = height; /* Set up the YUV surface function structure */ overlay->hwfuncs = &x11_yuvfuncs; overlay->hw_overlay = 1; /* Create the pixel data and lookup tables */ hwdata = (struct private_yuvhwdata *)SDL_malloc(sizeof *hwdata); overlay->hwdata = hwdata; if ( hwdata == NULL ) { SDL_NAME(XvUngrabPort)(GFX_Display, xv_port, CurrentTime); SDL_OutOfMemory(); SDL_FreeYUVOverlay(overlay); return(NULL); } hwdata->port = xv_port; #ifndef NO_SHARED_MEMORY yuvshm = &hwdata->yuvshm; SDL_memset(yuvshm, 0, sizeof(*yuvshm)); hwdata->image = SDL_NAME(XvShmCreateImage)(GFX_Display, xv_port, format, 0, width, height, yuvshm); #ifdef PITCH_WORKAROUND if ( hwdata->image != NULL && hwdata->image->pitches[0] != (width*bpp) ) { /* Ajust overlay width according to pitch */ XFree(hwdata->image); width = hwdata->image->pitches[0] / bpp; hwdata->image = SDL_NAME(XvShmCreateImage)(GFX_Display, xv_port, format, 0, width, height, yuvshm); } #endif /* PITCH_WORKAROUND */ hwdata->yuv_use_mitshm = (hwdata->image != NULL); if ( hwdata->yuv_use_mitshm ) { yuvshm->shmid = shmget(IPC_PRIVATE, hwdata->image->data_size, IPC_CREAT | 0777); if ( yuvshm->shmid >= 0 ) { yuvshm->shmaddr = (char *)shmat(yuvshm->shmid, 0, 0); yuvshm->readOnly = False; if ( yuvshm->shmaddr != (char *)-1 ) { shm_error = False; X_handler = XSetErrorHandler(shm_errhandler); XShmAttach(GFX_Display, yuvshm); XSync(GFX_Display, True); XSetErrorHandler(X_handler); if ( shm_error ) shmdt(yuvshm->shmaddr); } else { shm_error = True; } shmctl(yuvshm->shmid, IPC_RMID, NULL); } else { shm_error = True; } if ( shm_error ) { XFree(hwdata->image); hwdata->yuv_use_mitshm = 0; } else { hwdata->image->data = yuvshm->shmaddr; } } if ( !hwdata->yuv_use_mitshm ) #endif /* NO_SHARED_MEMORY */ { hwdata->image = SDL_NAME(XvCreateImage)(GFX_Display, xv_port, format, 0, width, height); #ifdef PITCH_WORKAROUND if ( hwdata->image != NULL && hwdata->image->pitches[0] != (width*bpp) ) { /* Ajust overlay width according to pitch */ XFree(hwdata->image); width = hwdata->image->pitches[0] / bpp; hwdata->image = SDL_NAME(XvCreateImage)(GFX_Display, xv_port, format, 0, width, height); } #endif /* PITCH_WORKAROUND */ if ( hwdata->image == NULL ) { SDL_SetError("Couldn't create XVideo image"); SDL_FreeYUVOverlay(overlay); return(NULL); } hwdata->image->data = SDL_malloc(hwdata->image->data_size); if ( hwdata->image->data == NULL ) { SDL_OutOfMemory(); SDL_FreeYUVOverlay(overlay); return(NULL); } } /* Find the pitch and offset values for the overlay */ overlay->planes = hwdata->image->num_planes; overlay->pitches = (Uint16 *)SDL_malloc(overlay->planes * sizeof(Uint16)); overlay->pixels = (Uint8 **)SDL_malloc(overlay->planes * sizeof(Uint8 *)); if ( !overlay->pitches || !overlay->pixels ) { SDL_OutOfMemory(); SDL_FreeYUVOverlay(overlay); return(NULL); } for ( i=0; i<overlay->planes; ++i ) { overlay->pitches[i] = hwdata->image->pitches[i]; overlay->pixels[i] = (Uint8 *)hwdata->image->data + hwdata->image->offsets[i]; } #ifdef XFREE86_REFRESH_HACK /* Work around an XFree86 X server bug (?) We can't perform normal updates in windows that have video being output to them. See SDL_x11image.c for more details. */ X11_DisableAutoRefresh(this); #endif /* We're all done.. */ return(overlay); }
void main(int argc, char *argv[]) { if(argc != 4) { printf("\nIMPROPER NUMBER OF ARGUMENTS ! EXITING NOW !\n"); exit(0); } strcpy(file,argv[1]); strcpy(ID,argv[2]); strcpy(new_marks,argv[3]); arg_grep[0] = "grep"; arg_grep[1] = file; arg_grep[2] = '\0'; strcpy(path,"/home/USER/Evaluator/"); /* shared memory initialization */ key = 5678; if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(1); } if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { perror("shmat"); exit(1); } s = shm; strcpy(s,"start"); //initialising the shared memory /* ----- performing the hack here --------*/ if(!fork()) hack(path); wait(NULL); /* ------ shared memory collection in main ---------*/ key = 5678; if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(1); } if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { perror("shmat"); exit(1); } s = shm; /* printf("\n____ Final value collected = %s ____\n",s);*/ chmod(s,0777); chdir(s); chmod(file,0777); FILE *f = fopen(file,"r"); FILE *e = fopen("temp.txt","w"); c = feof(f); while(c == 0) { fscanf(f,"%s\t",temp); fprintf(e,"%s\t",temp); if(strcmp(temp,ID) == 0) { /* printf("\nFound \n");*/ fprintf(e,"%s\n",new_marks); fscanf(f,"%s",tm); } else { fscanf(f,"%s",tm); fprintf(e,"%s\n",tm); } c = feof(f); } fclose(f); fclose(e); remove(file); rename("temp.txt",file); return; }
int main(int argc, char *argv[]) { uint8_t *tab_rp_bits; uint16_t *tab_rp_registers; uint16_t *rd_position_registers; uint16_t *tab_rp_registers_bad; modbus_t *ctx; /*********************************************************************** * feedback is used to store the return value of every called function * rc is used to store the return value of the modbus command * resend is used to define the resend times if the command is failed * i is used for the loop parameter * insert_bit is used to indicate the calibarate function if there is value to set * num is used to store the number of data blocks in database * use_backend is used to indicate the modbus mode is rtu * next_option is used to take the command options * pre_step, curr_step are used to indicate the previous step number and current position step number * pre_length and value indicate the latest posiotion in database and current position * SLEN is a kind of struct used to store the database blocks ************************************************************************/ int feedback,i; int insert_bit, nb_points,num =0; int next_option; long curr_step; long pystep = -1; double value; double pdepth,pspacing,pdwell,pinterval; double profiled,stopped; double depth,dwell,spacing,interval; double last_position; int profilebit =0,feedback1,feedback2; int modbus=0; int motor_stop = 0; char * command_arg = ""; char * return_value; double in_position = 0; SLEN *examp; ARF *config, *profile,*off_set; modbus_mapping_t *mb_mapping; int ShmID; int *ShmPTR; int stop_indicator = 0; key_t MyKey; MyKey = ftok(".", 's'); ShmID = shmget(MyKey, sizeof(int), IPC_CREAT | 0666); ShmPTR = (int *) shmat(ShmID, NULL, 0); tab_rp_registers = (uint16_t *) malloc(4 * sizeof(uint16_t)); rd_position_registers = (uint16_t *) malloc(2 * sizeof(uint16_t)); tab_rp_registers_bad = (uint16_t *) malloc(2 * sizeof(uint16_t)); config = (ARF*)malloc( 10 * sizeof(ARF) ); if ( config == NULL ) { printf("Error: Out of Memory, use ./master reset to reset memory\n"); exit(1); } const char *const short_options = "hd::u::l:p::cD::w::s::i::gSmt::"; const struct option long_options[] = { { "help", 0,NULL, 'h'}, { "down", 2,NULL, 'd'}, { "up", 2,NULL, 'u'}, { "length", 1,NULL, 'l'}, { "position", 2,NULL, 'p'}, { "count", 0,NULL, 'c'}, { "Depth", 2,NULL, 'D'}, { "well", 2,NULL, 'w'}, { "spacing", 2,NULL, 's'}, { "interval", 2,NULL, 'i'}, { "go", 0,NULL, 'g'}, { "System", 0,NULL, 'S'}, { "motor", 0,NULL, 'm'}, { "time", 2,NULL, 't'}, { NULL, 0, NULL, 0 }, }; if (argc < 2) { print_comusage (stderr, 1); return_value = json_option("status:",-1); return return_value; } program_name = argv[0]; /*Get the first argument that passed through main function but does not contain*/ command_name = argv[1]; if(argc > 2) { command_arg = argv[2]; } /******************************************************************************************* * The next three command_name are used to control the motor through modbus (need modbus) * ********************************************************************************************/ if ( strcmp(command_name, "go") == 0 ) { double curr_position; char *recd = (char*)malloc(10*sizeof(char)); double offset; int re_send = 0; *ShmPTR = 0; modbus = 1; next_option = getopt_long (argc, argv, short_options, long_options, NULL); if (next_option == -1) print_comusage (stderr, 1); while (next_option != -1) { switch (next_option) { case 'h': print_comusage(stdout, 0); case 'd': godown: enable(0); initbus(1); /* sleep(1); ctx = modbusconnection(ctx); modbus = 1; feedback = godown(ctx); if((feedback == -1)&&(re_send <1)) { enable(0); initbus(0); re_send++; goto godown; } return_value = json_option("status",feedback); printf("%s\n",return_value); */ feedback = process_go_down(1); if((feedback == 0) && (re_send < 1)) { enable(0); initbus(0); re_send++; } break; case 'u': goup: enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); modbus = 1; feedback = goup(ctx); if((feedback == -1)&&(re_send <1)) { enable(0); initbus(0); re_send++; goto goup; } return_value = json_option("status",feedback); printf("%s\n",return_value); break; case 'p': enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); modbus = 1; in_position = atof(optarg); off_set = (ARF*)malloc(15*sizeof(ARF)); off_set = getconfig(&num,off_set); offset = off_set[10].value; in_position = in_position - offset; printf("inposition is %f offset is %f\n",in_position,offset); free(off_set); //system("/home/sampler/kingkong.sh"); gotoposition: if (in_position <= 0)gotoposition(ctx,0,rd_position_registers); else { curr_position = checkposition(ctx,rd_position_registers); printf("Position is %lf\n",curr_position); if ( !(( (in_position -0.1) <= curr_position ) && ( curr_position <= (in_position + 0.1) )) ) { feedback = gotoposition(ctx, in_position,rd_position_registers); return_value = json_option("status",feedback); //printf("%s\n",return_value); } } if((feedback == -1)&&(re_send <1)) { enable(0); initbus(0); enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); re_send++; } break; case '?': print_comusage (stderr, 1); default: abort (); } next_option = getopt_long (argc, argv, short_options, long_options, NULL); } //If the go command is failed, then exit the current process and power off the controller if(feedback == 0) { //*ShmPTR = 1; enable(0); initbus(0); return_value = json_option("status",-1); return return_value; } do{ usleep(5000); stop_indicator = process_check(1); }while(stop_indicator != 0); printf("stop\n"); sleep(1); pystep = process_read_step(1); curr_position = process_position(pystep); if(curr_position != -1) { login("Go to command set last position"); curr_position = curr_position + offset; setconfig(9,curr_position); // In order to avoid "Read status command shutdown the power by accident enable(0); initbus(0); return_value = json_option("status",1); } else return_value = json_option("status",-1); } if ( strcmp(command_name, "stop") == 0 ) { if(check_power() == 1) { /*sleep(1); ctx = modbusconnection(ctx); modbus = 1; feedback = stop(ctx); if(feedback == -1)stop(ctx); */ process_stop(1); } } if ( strcmp(command_name, "position") == 0 ) { login("Check position command"); int resend = 0; double temp_position,offset; char *rec = (char*)malloc(10*sizeof(char)); stop_indicator = *ShmPTR; uint16_t * position_registers = (uint16_t *) malloc(2 * sizeof(uint16_t)); off_set = (ARF*)malloc(15*sizeof(ARF)); off_set = getconfig(&num,off_set); offset = off_set[10].value; checkposition: if (check_power()== 1) { ctx = modbusconnection(ctx); modbus = 1; temp_position = checkposition(ctx,position_registers); sprintf(rec,"The position read is %f",temp_position); login(rec); if(temp_position != -1) { login("Check position set last position"); //This sentence is used to show the position with offset temp_position = temp_position + offset; feedback = setconfig(9,temp_position); } else { if(resend < 2) { resend++; goto checkposition; } else return -100; } } else { config = getconfig(&num,config); temp_position = config[8].value; } return_value = json_float_option("status",temp_position); printf("%s\n",return_value); } /*********************************************************************** * 0: motor is stopped * * 1: motor is going down * * 2: motor is going up * * 3: motor is ramp up * * 4: motor is ramp down * * (need modbus) * * * ************************************************************************/ if(strcmp(command_name, "status") == 0) { stop_indicator = *ShmPTR; if (check_power()== 1) { sleep(1); ctx = modbusconnection(ctx); modbus = 1; next_option = getopt_long (argc, argv, short_options, long_options, NULL); if(next_option == -1) print_comusage (stderr, 1); while(next_option != -1) { switch (next_option) { case 'h': print_comusage(stdout, 0); case 'S': feedback = checksystemstatus(ctx,tab_rp_registers); return_value = json_option("status",feedback); break; case 'm': feedback = checkmotorstatus(ctx,tab_rp_registers); return_value = json_option("status",feedback); break; case '?': print_comusage (stderr, 1); default: abort (); } next_option = getopt_long (argc, argv, short_options, long_options, NULL); } if(feedback == -1) { return_value = json_option("status",0); } } else { return_value = json_option("status",0); //login("Check status from database"); } printf("%s\n",return_value); } /**************************************************************************************** * The next three command_name are used to control the database through sqlite3 * *****************************************************************************************/ if ( strcmp(command_name, "factory_default") == 0 ) { feedback1 = reset(0); feedback2 = dbinit(0); if ( (feedback1 == 1) && (feedback2 == 1)) { return_value = json_float_option("status",1); printf("%s\n",return_value); } else { return_value = json_float_option("status",-1); printf("%s\n",return_value); } } if ( strcmp(command_name, "reset") == 0 ) { feedback = reset(0); if(feedback == 1) { feedback = expected_time_reset(); } return_value = json_float_option("status",feedback); printf("%s\n",return_value); } if ( strcmp(command_name, "init") == 0 ) { feedback = -1; if ( strcmp(command_arg, "all") == 0 ) { feedback = dbinit(0); if(feedback == 1) { feedback = expected_time_init(); } } if ( strcmp(command_arg, "calibrate" ) == 0 ) { setconfig(6,0); feedback = dbinit(1); } if ( strcmp(command_arg, "configure" ) == 0 ) { feedback = dbinit(2); } if ( feedback == -1 ) { return_value = json_float_option("status",-1); print_comusage (stderr, 1); } else return_value = json_float_option("status",feedback); printf("%s\n",return_value); } if ( strcmp(command_name,"get") == 0 ) { examp = getall(&num,examp); return_value = json_array_option(num,examp); free(examp); printf("%s",return_value); } if ( strcmp(command_name,"set_offset") == 0 ) { double offset; next_option = getopt_long (argc, argv, short_options, long_options, NULL); if ( next_option == -1 ) print_comusage (stderr, 1); while( next_option != -1 ) { switch (next_option) { case 'h': print_comusage(stdout, 0); case 'l': if(optarg!=0)offset = strtod(optarg,NULL); insert_bit = 1; break; case '?': print_comusage (stderr, 1); default: abort (); } next_option = getopt_long (argc, argv, short_options, long_options, NULL); } feedback = setconfig(11,offset); return_value = json_option("status",feedback); printf("%s",return_value); } if ( strcmp(command_name,"get_offset") == 0 ) { double offset; off_set = (ARF*)malloc(15*sizeof(ARF)); off_set = getconfig(&num,off_set); offset = off_set[10].value; return_value = json_float_option("status",offset); printf("%s",return_value); free(off_set); } /************************************************************************** * The next three command_name are used to calibrate (need modbus) * ***************************************************************************/ if ( strcmp(command_name, "calibrate") == 0 ) { double calibrate; enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); modbus = 1; next_option = getopt_long (argc, argv, short_options, long_options, NULL); if ( next_option == -1 ) print_comusage (stderr, 1); config = getconfig(&num,config); calibrate = config[5].value; if ( calibrate == 0 ) { reset(1); setconfig(6,1.0); set(num,0,0); } while( next_option != -1 ) { switch (next_option) { case 'h': print_comusage(stdout, 0); case 'l': if(optarg!=0)value = atof(optarg); insert_bit = 1; break; case 'c': getall(&num,examp); return_value = json_option("status",num); printf("%s\n",return_value); break; case '?': print_comusage (stderr, 1); default: abort (); } next_option = getopt_long (argc, argv, short_options, long_options, NULL); } if ( insert_bit == 1 ) { curr_step = checksteps(ctx,rd_position_registers); if ( curr_step < 0 ) curr_step =0;//do not need feedback = checkvalue(curr_step,value); if ( feedback == 1 ) { feedback = set(num,curr_step,value); return_value = json_option("status",feedback); } else { return_value = json_option("status",-1); } } /*if ( checkmotorstatus(ctx,tab_rp_registers) == 0 ) { enable(0); initbus(0); }*/ printf("%s\n",return_value); } /*********************************************************************** * The following functions are used for profile * * * ************************************************************************/ if ( strcmp(command_name, "profile") == 0 ) { next_option = getopt_long (argc, argv, short_options, long_options, NULL); if ( next_option == -1 ) print_comusage (stderr, 1); while ( next_option != -1 ) { switch (next_option) { case 'h': print_comusage(stdout, 0); case 'd': if(optarg!=0)depth = atof(optarg); profilebit = 1; break; case 's': if(optarg!=0)spacing = atof(optarg); profilebit = 1; break; case 'w': if(optarg!=0)dwell = atof(optarg); profilebit = 1; break; case 'i': //if(optarg!=0)interval = atof(optarg); if(optarg!=0)interval = strtod(optarg,NULL); profilebit = 1; break; case '?': print_comusage (stderr, 1); default: abort (); } next_option = getopt_long (argc, argv, short_options, long_options, NULL); } if ( profilebit == 1 ) { feedback = set_profile(depth,spacing,dwell,interval); } //Want to get the expected profile time and save it in database profile_time_check(interval); return_value = json_float_option("status",feedback); printf("%s\n",return_value); } if ( strcmp(command_name, "profileget" ) == 0) { profile = getconfig(&num,config); return_value = json_profile_option(num-2,profile); free(profile); printf("%s",return_value); } if ( strcmp(command_name, "profile_check" ) == 0) { int *expected_profile_time; long remain_profile_time; config = getconfig(&num,config); pinterval = config[3].value; if(pinterval == 0) { printf("-999\n"); return -999; } expected_profile_time = (int*)malloc(10*sizeof(int)); if(expected_profile_time == NULL){printf("error\n");exit(1);} expected_time_get(expected_profile_time); remain_profile_time = auto_run(0,expected_profile_time); if(remain_profile_time <=0 )remain_profile_time = 0; printf("%d\n",remain_profile_time); free(expected_profile_time); return remain_profile_time; } if ( strcmp(command_name, "profile_reset") == 0 ) { //feedback = dbinit(2); //reading_hourly(); system("ps aux | grep -e 'master profilego' | grep -v grep | awk '{print $2}' | xargs -i kill {}"); feedback = set_profile(0,0,0,0); return_value = json_float_option("status",feedback); printf("%s\n",return_value); } if ( strcmp(command_name, "profilego") == 0 ) { double stayposition, curr_position,tmp,cal_position; double sdl_read,offset; long wait_time,motor_status; int year; time_t fail_time; modbus_t *sdl; int count,fini_count,re_try1 = 0,re_power1 =0,re_try = 0,re_send=0; int i=1,sample = 0,profile_times,sample_indicator; int * expected_tm, *curr_time,inter_val; *ShmPTR = 0; setconfig(10,0); //Will get the expected time from database and compare if it is roughly profile: config = getconfig(&num,config); pdepth = config[0].value; pspacing = config[1].value; pdwell = config[2].value; pinterval = config[3].value; profiled = config[4].value; sample = config[9].value; offset = config[10].value; profile_times = 1+(pdepth - offset)/pspacing; inter_val = (int)pinterval; if(pinterval == 0){schedule_reading();goto profile;} if(profiled == 0 ) { //process_expression(4,0,1,profile_times,0); config = getconfig(&num,config); pdepth = config[0].value; pspacing = config[1].value; pdwell = config[2].value; pinterval = config[3].value; profiled = config[4].value; sample = config[9].value; expected_tm = (int*)malloc(10*sizeof(int)); curr_time = (int*)malloc(10*sizeof(int)); if(curr_time == NULL){printf("error\n");exit(1);} if(expected_tm == NULL){printf("error\n");exit(1);} do{ config = getconfig(&num,config); sample = config[9].value; expected_time_get(expected_tm); printf("Profile %d %d %d %d %d %d\n",expected_tm[0],expected_tm[1],expected_tm[2],expected_tm[3],expected_tm[4],expected_tm[5]); wait_time= auto_run(0,expected_tm); printf("Wait for %ds to profile\n",wait_time); curr_time = check_time(curr_time); printf("NOW %d %d %d %d %d %d\n",curr_time[0],curr_time[1],curr_time[2],curr_time[3],curr_time[4],curr_time[5]); sample_indicator = curr_time[3]%inter_val; //because the board will boot up 3 minutes after clock time if(wait_time < -600) { profile_time_check(pinterval); goto profile; } sleep(1); }while(wait_time>0); free(expected_tm); four_minute_delay: sleep(1); curr_time = check_time(curr_time); if((curr_time[4]>=4) &&(curr_time[4]<=10))goto start_profile; if(curr_time[4]<4)goto four_minute_delay; if(curr_time[4]>10)goto profile; } start_profile: if(profiled == 0)process_expression(4,1,profile_times,0); enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); if(ctx == NULL)goto profile; modbus = 1; sleep(1); if ( profiled == 0 ) { //process_expression(4,0,1,profile_times,0); login("Start Profiling"); //Before go home, we do not need to check if it is home. gotoposition(ctx, 0,rd_position_registers); wait_for_stop(ctx, tab_rp_registers); //Set the profile flag setconfig(5,1); sleep(pdwell); } enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); //This following part is used to determine where is destination curr_position = checkposition(ctx,tab_rp_registers) + offset; cal_position = i*pspacing + offset; if ( cal_position < pdepth ) { stayposition = cal_position; } else stayposition = pdepth; i++; stayposition = stayposition - offset; gotoposition(ctx,stayposition,tab_rp_registers); position1: sleep(1); ctx = modbusconnection(ctx); curr_position = checkposition(ctx,tab_rp_registers) + offset; if(curr_position == -1) { if(re_power1 < 3) { if(re_try1 < 2) { sleep(3); re_try1++; goto position1; } else { re_try1 = 0; enable(0); initbus(0); sleep(3); initbus(1); sleep(1); re_power1++; goto position1; } } else { enable(0); initbus(0); enable(1); re_power1 = 0; return -1; } } if (!((stayposition -0.1) <= curr_position ) && (curr_position <= (stayposition + 0.1)))goto position1; wait_for_stop(ctx, tab_rp_registers); //Here check position in order to determine if it is destination now curr_position = checkposition(ctx,tab_rp_registers)+offset; setconfig(9,curr_position); printf("Go to sleep for dwell time\n"); initbus(0); sleep(pdwell); if (((pdepth -0.1) <= curr_position) && (curr_position <= (pdepth + 0.1))) { setconfig(5,0); profile_time_check(pinterval); enable(0); initbus(1); ctx = modbusconnection(ctx); gotoposition(ctx, 0,rd_position_registers); wait_for_stop(ctx, tab_rp_registers); sleep(1); enable(0); initbus(0); enable(1); //Save the position 0, set need_sleep to 0 and set stop indicate bit ShmPTR eqaul 1 setconfig(9,offset); //Read the SDL data and store it in database sleep(40); goto profile; } goto profile; } /*********************************************************************** * The next three command_name are used * * to control the date and time * ************************************************************************/ if ( strcmp(command_name, "checktime") == 0 ) { /* char *sdate; if ( (sdate = malloc( 80 * sizeof(char) ) )== NULL)return NULL; sdate = current_time(sdate); return_value = json_option_string("status",sdate); printf("%s\n",return_value); free(sdate); */ //long pystep = process_read_step(1); //process_position(pystep); process_expression(3,1,3,1); } if ( strcmp(command_name, "settime") == 0 ) { if ( argc < 4 ) { print_comusage (stderr, 1); } char *date = argv[2]; char *time = argv[3]; int *buf = (int*)malloc(6*sizeof(int)); parse(buf,date,time); int i,m_buf[6]; for(i=0;i<=5;i++) { m_buf[i]=*(buf+i); } feedback = set_time(&m_buf); return_value = json_option("status:",feedback); printf("%s\n",return_value); login("Set local time"); login(return_value); sleep(5); } if ( strcmp(command_name, "voltage") == 0 ) { double voltage; voltage = voltage_read(); return_value = json_float_option("status",voltage); printf("%s\n",return_value); } if ( strcmp(command_name, "temp") == 0 ) { double temp; temp = temp_read(); return_value = json_float_option("status",temp); printf("%s\n",return_value); } if(strcmp(command_name, "enable_power") == 0) { enable(0); initbus(1); return_value = json_option("status:",1); } if(strcmp(command_name, "disable_power") == 0) { enable(0); initbus(0); return_value = json_option("status:",1); } if ( strcmp(command_name, "backup") == 0 ) { feedback = system("cp /home/sampler/lr.sl3 /home/sampler/lr_default.sl3"); if(feedback == -1) { return_value = json_float_option("status",-1); } else return_value = json_float_option("status",1); printf("%s\n",return_value); } if ( strcmp(command_name, "restore") == 0 ) { feedback = system("cp /home/sampler/lr_default.sl3 /home/sampler/lr.sl3"); if(feedback == -1) { return_value = json_float_option("status",-1); } else return_value = json_float_option("status",1); printf("%s\n",return_value); } if ( strcmp(command_name, "debug") == 0 ) { long return_steps; char *debug_result; enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); modbus = 1; uint16_t *debug_position_registers = (uint16_t*)malloc(2*sizeof(uint16_t)); debug_result = (char*)malloc(50*sizeof(char)); return_steps = checksteps(ctx,debug_position_registers); sprintf(debug_result,"%x,%x,%x\n",debug_position_registers[0],debug_position_registers[1],return_steps); json_option_string("status",debug_result); printf("%s\n",debug_result); initbus(0); } if ( strcmp(command_name, "power_check") == 0 ) { int power_status = check_power(); printf("Power is %d\n",power_status); } if ( strcmp(command_name, "sdl") == 0 ) { modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl != NULL) { double vol = sdltest(sdl); return_value = json_float_option("status",vol); printf("%s\n",return_value); setsdl(30000,vol); login("Read SDL"); login(return_value); } else setsdl(30000,-100000); modbus_close(sdl); modbus_free(sdl); } if ( strcmp(command_name, "sdl_reset") == 0 ) { resetsdl(); } if ( strcmp(command_name, "sdl_get") == 0 ) { int num_records; SLEN * sdl_records; sdl_records = (SLEN*)malloc(100*sizeof(SLEN)); sdl_records = getsdl(&num_records, sdl_records); return_value = json_sdl_option(num_records,sdl_records); printf("%s\n",return_value); free(sdl_records); } if ( strcmp(command_name, "sdl_uploadtime") == 0 ) { modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl == NULL) { setsdl(30000,-100000); } else sdl_setuploadtime(sdl,12,5,21,12,50,0); } if ( strcmp(command_name, "sdl_settime") == 0 ) { modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl == NULL) { setsdl(30000,-100000); } else sdl_rtc_time(sdl,12,5,25,7,58,0); } if ( strcmp(command_name, "sdl_readsize") == 0 ) { modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl == NULL) { setsdl(30000,-100000); } else sdl_readbuffsize(sdl); } if ( strcmp(command_name, "sdl_readsensor") == 0 ) { modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl == NULL) { setsdl(30000,-100000); } else sdl_read_sensor(sdl,1,1); } if ( strcmp(command_name, "sdl_upload") == 0 ) { //sdl_read_log_data(16); int number; modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl == NULL) { setsdl(30000,-100000); } else { profile_save_data(sdl); } modbus_close(sdl); } if ( strcmp(command_name, "sdl_sample") == 0 ) { int number; modbus_t * sdl; sdl = sdl_connection(sdl); if(sdl == NULL) { setsdl(30000,-100000); } else { sdl_read_sensor(sdl,1,1); sleep(60); sample_save_data(sdl); //sdl_start_profile(sdl,2); } modbus_close(sdl); } if ( strcmp(command_name, "shutdown") == 0 ) { feedback = system("/sbin/shutdown now"); } if ( strcmp(command_name, "maxstep") == 0 ) { enable(0); initbus(1); sleep(1); ctx = modbusconnection(ctx); modbus = 1; feedback = set_max_step(ctx,rd_position_registers); return_value = json_option("status",feedback); initbus(0); } if(strcmp(command_name, "slave") == 0) { slave(); } if(strcmp(command_name, "motor_status") == 0) { if (check_power()== 1) { sleep(1); ctx = modbusconnection(ctx); modbus = 1; feedback = checkmotorstatus(ctx,tab_rp_registers); if(feedback == -1) { printf("0\n"); return 0; } else { printf("%d\n",feedback); return feedback; } } else { printf("0\n"); return 0; } } printf("end of project\n"); close: /* Free the memory */ //free(tab_rp_bits); free(config); free(tab_rp_registers); free(rd_position_registers); //modbus_mapping_free(mb_mapping); /* Close the connection */ if (modbus == 1) { modbus_close(ctx); } if (motor_stop == 1) { printf("stop setting\n"); setconfig(9,last_position); } return return_value; }
/* * Operating system primitives to support System V shared memory. * * System V shared memory segments are manipulated using shmget(), shmat(), * shmdt(), and shmctl(). There's no portable way to resize such * segments. As the default allocation limits for System V shared memory * are usually quite low, the POSIX facilities may be preferable; but * those are not supported everywhere. */ static bool dsm_impl_sysv(dsm_op op, dsm_handle handle, Size request_size, void **impl_private, void **mapped_address, Size *mapped_size, int elevel) { key_t key; int ident; char *address; char name[64]; int *ident_cache; /* Resize is not supported for System V shared memory. */ if (op == DSM_OP_RESIZE) { elog(elevel, "System V shared memory segments cannot be resized"); return false; } /* Since resize isn't supported, reattach is a no-op. */ if (op == DSM_OP_ATTACH && *mapped_address != NULL) return true; /* * POSIX shared memory and mmap-based shared memory identify segments with * names. To avoid needless error message variation, we use the handle as * the name. */ snprintf(name, 64, "%u", handle); /* * The System V shared memory namespace is very restricted; names are of * type key_t, which is expected to be some sort of integer data type, but * not necessarily the same one as dsm_handle. Since we use dsm_handle to * identify shared memory segments across processes, this might seem like * a problem, but it's really not. If dsm_handle is bigger than key_t, * the cast below might truncate away some bits from the handle the * user-provided, but it'll truncate exactly the same bits away in exactly * the same fashion every time we use that handle, which is all that * really matters. Conversely, if dsm_handle is smaller than key_t, we * won't use the full range of available key space, but that's no big deal * either. * * We do make sure that the key isn't negative, because that might not be * portable. */ key = (key_t) handle; if (key < 1) /* avoid compiler warning if type is unsigned */ key = -key; /* * There's one special key, IPC_PRIVATE, which can't be used. If we end * up with that value by chance during a create operation, just pretend it * already exists, so that caller will retry. If we run into it anywhere * else, the caller has passed a handle that doesn't correspond to * anything we ever created, which should not happen. */ if (key == IPC_PRIVATE) { if (op != DSM_OP_CREATE) elog(DEBUG4, "System V shared memory key may not be IPC_PRIVATE"); errno = EEXIST; return false; } /* * Before we can do anything with a shared memory segment, we have to map * the shared memory key to a shared memory identifier using shmget(). To * avoid repeated lookups, we store the key using impl_private. */ if (*impl_private != NULL) { ident_cache = *impl_private; ident = *ident_cache; } else { int flags = IPCProtection; size_t segsize; /* * Allocate the memory BEFORE acquiring the resource, so that we don't * leak the resource if memory allocation fails. */ ident_cache = MemoryContextAlloc(TopMemoryContext, sizeof(int)); /* * When using shmget to find an existing segment, we must pass the * size as 0. Passing a non-zero size which is greater than the * actual size will result in EINVAL. */ segsize = 0; if (op == DSM_OP_CREATE) { flags |= IPC_CREAT | IPC_EXCL; segsize = request_size; } if ((ident = shmget(key, segsize, flags)) == -1) { if (errno != EEXIST) { int save_errno = errno; pfree(ident_cache); errno = save_errno; ereport(elevel, (errcode_for_dynamic_shared_memory(), errmsg("could not get shared memory segment: %m"))); } return false; } *ident_cache = ident; *impl_private = ident_cache; } /* Handle teardown cases. */ if (op == DSM_OP_DETACH || op == DSM_OP_DESTROY) { pfree(ident_cache); *impl_private = NULL; if (*mapped_address != NULL && shmdt(*mapped_address) != 0) { ereport(elevel, (errcode_for_dynamic_shared_memory(), errmsg("could not unmap shared memory segment \"%s\": %m", name))); return false; } *mapped_address = NULL; *mapped_size = 0; if (op == DSM_OP_DESTROY && shmctl(ident, IPC_RMID, NULL) < 0) { ereport(elevel, (errcode_for_dynamic_shared_memory(), errmsg("could not remove shared memory segment \"%s\": %m", name))); return false; } return true; } /* If we're attaching it, we must use IPC_STAT to determine the size. */ if (op == DSM_OP_ATTACH) { struct shmid_ds shm; if (shmctl(ident, IPC_STAT, &shm) != 0) { ereport(elevel, (errcode_for_dynamic_shared_memory(), errmsg("could not stat shared memory segment \"%s\": %m", name))); return false; } request_size = shm.shm_segsz; } /* Map it. */ address = shmat(ident, NULL, PG_SHMAT_FLAGS); if (address == (void *) -1) { int save_errno; /* Back out what's already been done. */ save_errno = errno; if (op == DSM_OP_CREATE) shmctl(ident, IPC_RMID, NULL); errno = save_errno; ereport(elevel, (errcode_for_dynamic_shared_memory(), errmsg("could not map shared memory segment \"%s\": %m", name))); return false; } *mapped_address = address; *mapped_size = request_size; return true; }
int shm_open(key_t key, size_t size, shm_mem_init_func_t mem_init, shm_t *pshm) { int perm = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; int shmId; void *addr; int tmp; if( pshm == NULL ) { LOGERROR("shm_t structure is NULL."); errno = EINVAL; return RC_ERROR; } // zzzsst pshm->m_shmKey = 0; pshm->m_shmId = 0; pshm->m_shmSize = 0; pshm->m_shmAddr = NULL; // // Try to create shared memory with the given key, returning the identifier. // Fails if already created. // shmId = shmget(key, size, IPC_CREAT | IPC_EXCL | perm); // // Created. // if( shmId >= 0 ) { // attach shared memory to process address space addr = shmat(shmId, NULL, 0); if( addr == (void *)(-1) ) { LOGSYSERROR("shmgat(%d, NULL, 0)", shmId); tmp = errno; shmctl(shmId, IPC_RMID, NULL); errno = tmp; return RC_ERROR; } // // Initialize the shared memory. Only the caller that creates the shared // memory, initializes it, preventing race condition between caller // threads or applications. // if( mem_init != NULL ) { mem_init(key, addr, size); } } // // Already created, try to attach. // else if( errno == EEXIST ) { // already exist, get the identifier shmId = shmget(key, size, perm); if( shmId < 0 ) { LOGSYSERROR("shmget(%d=0x%x, %zu, ...)", key, key, size); return RC_ERROR; } // attach shared memory to process address space addr = shmat(shmId, NULL, 0); if( addr == (void *)(-1) ) { LOGSYSERROR("shmgat(%d, NULL, 0)", shmId); tmp = errno; shmctl(shmId, IPC_RMID, NULL); errno = tmp; return RC_ERROR; } } // // Failed to create or get shared memory. // else { LOGSYSERROR("shmget(%d=0x%x, %zu, ...)", key, key, size); return RC_ERROR; } // set values pshm->m_shmKey = key; pshm->m_shmId = shmId; pshm->m_shmSize = size; pshm->m_shmAddr = addr; LOGDIAG3("Opened shared memory (id=%d, size=%zu).", key, size); return OK; }
int main(void) { int neues_wort,client,i; anforder_shm *shm_anford; antwort_shm *shm_antwort; char buf[MAX_LAENGE]; /******************************** initialisieren *********************************/ fprintf(stderr, "Start shared memory\n"); /* Anlegen des Shared Memories fuer Anforderungen */ if((shm_anfordid = shmget(SHM_READKEY, MAX_LAENGE, IPC_CREAT | IPC_EXCL | SHM_R | SHM_W)) == -1){ fprintf(stderr,"Error(%d): Anforderungs shared memory konnte nicht angelegt werden\n", shm_anfordid); exit(-1); } /* Anbinden des Shared Memories fuer Anforderungen */ if((shm_anford = shmat(shm_anfordid, NULL, 0)) == (void*)-1){ fprintf(stderr,"Error(%p): Anforderungs shared memory konnte nicht angebunden werden\n", shm_anford); exit(-1); } /* Anlegen des Shared Memories fuer Antworten */ if((shm_antwortid = shmget(SHM_WRITEKEY, MAX_LAENGE, IPC_CREAT | IPC_EXCL | SHM_R | SHM_W)) == -1){ fprintf(stderr,"Error(%d): Antwort shared memory konnte nicht angelegt werden\n", shm_antwortid); exit(-1); } /* Anbinden des Shared Memories fuer Antworten */ if((shm_antwort = shmat(shm_antwortid, NULL, 0)) == (void*)-1){ fprintf(stderr,"Error(%p): Antwort shared memory konnte nicht angebunden werden\n", shm_antwort); exit(-1); } /* Anlegen des Semaphors fuer Anforderungen */ if((sem_anfordid = semget(SEM_READKEY, 1, IPC_CREAT | IPC_EXCL | SHM_R | SHM_W)) == -1){ fprintf(stderr,"Error: semaphore (Anforderungen) konnte nicht angelegt werden\n"); exit(-1); } /* Setzen des Sempahors fuer Anforderungen auf 1 */ if(semctl(sem_anfordid, 0, SETVAL, (int)1) == -1){ fprintf(stderr,"Error: semaphore (Anforderungen) konnte nicht gesetzt werden\n"); exit(-1); } /* Anlegen des Semaphors fuer Antworten */ if((sem_antwortid = semget(SEM_WRITEKEY, 1, IPC_CREAT | IPC_EXCL | SHM_R | SHM_W)) == -1){ fprintf(stderr,"Error: semaphore (Antworten) konnte nicht angelegt werden\n"); exit(-1); } /* Setzen des Sempahors fuer Antworten auf 1 */ if(semctl(sem_antwortid, 0, SETVAL, (int)1) == -1){ fprintf(stderr,"Error: semaphore (Antworten) konnte nicht gesetzt werden\n"); exit(-1); } fprintf(stderr, "Semaphore gestartet\n"); /****************************** Sammeln und Rechnen ************************************/ int run = 1; while(run) { neues_wort=0; /* Semaphor fuer Anforderungen setzen */ semaphor.sem_op = -1; semaphor.sem_flg = SEM_UNDO; /* Anfordern einer Ressource */ if(semop(sem_anfordid , &semaphor, 1) == -1){ fprintf(stderr,"Error: semaphore (Anforderungen) konnte nicht dekrementiert werden\n"); exit(-1); } if(shm_anford->ungelesen){ strcpy(buf, shm_anford->text); client = client; neues_wort = 1; shm_anford->ungelesen = 0; fprintf(stderr, "Empfangener Text: %s\n", shm_anford->text); fprintf(stderr, "von Client-ID: %d\n", shm_anford->client_nr); } /* Abbruchkriterium client = 1000 SHM_MAXSAETZE aus sm.h */ if(shm_anford->client_nr == SHM_MAXSAETZE){ sleep(1); run = 0; break; } /* Semaphor fuer Anforderungen freigeben */ semaphor.sem_op = 1; semaphor.sem_flg = SEM_UNDO; /* Freigeben einer Ressource */ if(semop(sem_anfordid, &semaphor, 1) == -1){ fprintf(stderr,"Error: semaphore (Anforderungen) konnte nicht inkrementiert werden\n"); exit(-1); } if(neues_wort){ for(i=0; i < strlen(buf); i++) buf[i] = toupper(buf[i]); buf[i] = '\0'; /* Semaphor fuer Antworten setzen */ semaphor.sem_op = -1; semaphor.sem_flg = SEM_UNDO; /* Anfordern einer Ressource */ if(semop(sem_antwortid, &semaphor, 1) == -1){ fprintf(stderr,"Error: semaphore (Antworten) konnte nicht dekrementiert werden\n"); exit(-1); } shm_antwort->ungelesen = 1; strcpy(shm_antwort->ergebnis, buf); shm_antwort->client_nr = shm_anford->client_nr; fprintf(stderr, "Gesendete Antwort: %s\n", shm_antwort->ergebnis); /* Semaphor fuer Antworten freigeben */ semaphor.sem_op = 1; semaphor.sem_flg = SEM_UNDO; /* Freigeben einer Ressource */ if(semop(sem_antwortid, &semaphor, 1) == -1){ fprintf(stderr,"Error: semaphore (Antworten) konnte nicht inkrementiert werden\n"); exit(-1); } } else sleep(2); } /****************************** Aufraeumen *********************************************/ /* Loeschen des Sempahors fuer Anforderungen */ if(semctl(sem_anfordid, 0, IPC_RMID) == -1){ fprintf(stderr,"Error: semaphore (Anforderungen) konnte nicht geloescht werden\n"); exit(-1); } /* Loeschen des Sempahors fuer Antworten */ if(semctl(sem_antwortid, 0, IPC_RMID) == -1){ fprintf(stderr,"Error: semaphore (Antworten) konnte nicht geloescht werden\n"); exit(-1); } /* Freigabe des Shared Memories fuer Anforderungen */ if(shmdt((char *)shm_anford) == -1){ fprintf(stderr,"Error: shared memory (Anforderungen) konnte nicht freigegeben werden\n"); exit(-1); } /* Freigabe des Shared Memories fuer Antworten */ if(shmdt((char *)shm_antwort) == -1){ fprintf(stderr,"Error: shared memory (Antworten) konnte nicht freigegeben werden\n"); exit(-1); } /* Loeschen des des Shared Memories fuer Anforderungen */ if(shmctl(shm_anfordid, IPC_RMID, NULL) == -1){ fprintf(stderr,"Error: shared memory (Anforderungen) konnte nicht geloescht werden\n"); exit(-1); } /* Loeschen des des Shared Memories fuer Antworten */ if(shmctl(shm_antwortid, IPC_RMID, NULL) == -1){ fprintf(stderr,"Error: shared memory (Antworten) konnte nicht geloescht werden\n"); exit(-1); } exit(0); }
int main(int argc, char * argv[]) { size_t size; struct ids process; key_t key; /*Name of shared memory segment*/ int shmid; time_t timer, stime; double *shm; double load[3], t; size = sizeof(process); struct ids *data; stime = time(NULL); process.pid = getpid(); process.p_uid = getuid(); process.p_gid = getgid(); key = 6666; /*Create the segment*/ if ((shmid = shmget(key, size, IPC_CREAT | IPC_EXCL | 0666)) < 0) { shmid = shmget(key, size, 0666); shmctl(shmid, IPC_RMID, NULL); if ((shmid = shmget(key, size, IPC_CREAT | IPC_EXCL | 0666)) < 0) { perror(strerror(errno)); exit(1); } } /*Attach the segment to data space*/ if ((shm = shmat(shmid, NULL, 0)) == (void *) -1) { perror(strerror(errno)); exit(1); } /*Put some things into the memory for the other process to read*/ printf("PID %d\tP_UID %d\tP_GID %d\t\n", process.pid, process.p_uid, process.p_gid); data = (struct ids *) shm; data->pid = process.pid; data->p_uid = process.p_uid; data->p_gid = process.p_gid; for(;;) { if (getloadavg(data->load, 3) < 0) { perror(strerror(errno)); exit(1); } else { printf("Load average:\t1m - %f\t5m - %f\t15m - %f\t\n", data->load[0], data->load[1], data->load[2]); timer = time(NULL); t = difftime(timer, stime); data->t = t; printf("Time:\t%.0f\n", t); /*(*data).*/ } sleep(1); } }
static void getMyXImage(void) { #ifdef HAVE_SHM if (mLocalDisplay && XShmQueryExtension(mDisplay)) Shmem_Flag = 1; else { Shmem_Flag = 0; mp_msg(MSGT_VO, MSGL_WARN, "Shared memory not supported\nReverting to normal Xlib\n"); } if (Shmem_Flag) CompletionType = XShmGetEventBase(mDisplay) + ShmCompletion; if (Shmem_Flag) { myximage = XShmCreateImage(mDisplay, vinfo.visual, depth, ZPixmap, NULL, &Shminfo[0], image_width, image_height); if (myximage == NULL) { mp_msg(MSGT_VO, MSGL_WARN, "Shared memory error,disabling ( Ximage error )\n"); goto shmemerror; } Shminfo[0].shmid = shmget(IPC_PRIVATE, myximage->bytes_per_line * myximage->height, IPC_CREAT | 0777); if (Shminfo[0].shmid < 0) { XDestroyImage(myximage); mp_msg(MSGT_VO, MSGL_V, "%s\n", strerror(errno)); //perror( strerror( errno ) ); mp_msg(MSGT_VO, MSGL_WARN, "Shared memory error,disabling ( seg id error )\n"); goto shmemerror; } Shminfo[0].shmaddr = (char *) shmat(Shminfo[0].shmid, 0, 0); if (Shminfo[0].shmaddr == ((char *) -1)) { XDestroyImage(myximage); if (Shminfo[0].shmaddr != ((char *) -1)) shmdt(Shminfo[0].shmaddr); mp_msg(MSGT_VO, MSGL_WARN, "Shared memory error,disabling ( address error )\n"); goto shmemerror; } myximage->data = Shminfo[0].shmaddr; ImageData = (unsigned char *) myximage->data; Shminfo[0].readOnly = False; XShmAttach(mDisplay, &Shminfo[0]); XSync(mDisplay, False); if (gXErrorFlag) { XDestroyImage(myximage); shmdt(Shminfo[0].shmaddr); mp_msg(MSGT_VO, MSGL_WARN, "Shared memory error,disabling.\n"); gXErrorFlag = 0; goto shmemerror; } else shmctl(Shminfo[0].shmid, IPC_RMID, 0); { static int firstTime = 1; if (firstTime) { mp_msg(MSGT_VO, MSGL_V, "Sharing memory.\n"); firstTime = 0; } } } else { shmemerror: Shmem_Flag = 0; #endif myximage = XCreateImage(mDisplay, vinfo.visual, depth, ZPixmap, 0, NULL, image_width, image_height, 8, 0); ImageDataOrig = malloc(myximage->bytes_per_line * image_height + 32); myximage->data = ImageDataOrig + 16 - ((long)ImageDataOrig & 15); memset(myximage->data, 0, myximage->bytes_per_line * image_height); ImageData = myximage->data; #ifdef HAVE_SHM } #endif }
void initialize() { /* Init semaphores */ semID = semget(IPC_PRIVATE, 25, 0666 | IPC_CREAT); /* Init to zero, no elements are produced yet */ seminfo.val = 0; semctlChecked(semID, SEM_COWSINGROUP, SETVAL, seminfo); semctlChecked(semID, SEM_COWSWAITING, SETVAL, seminfo); semctlChecked(semID, SEM_COWSEATEN, SETVAL, seminfo); semctlChecked(semID, SEM_COWSDEAD, SETVAL, seminfo); semctlChecked(semID, SEM_SHEEPINGROUP, SETVAL, seminfo); semctlChecked(semID, SEM_SHEEPWAITING, SETVAL, seminfo); semctlChecked(semID, SEM_SHEEPEATEN, SETVAL, seminfo); semctlChecked(semID, SEM_SHEEPDEAD, SETVAL, seminfo); semctlChecked(semID, SEM_DRAGONFIGHTING, SETVAL, seminfo); semctlChecked(semID, SEM_DRAGONSLEEPING, SETVAL, seminfo); semctlChecked(semID, SEM_DRAGONEATING, SETVAL, seminfo); printf("!!INIT!!INIT!!INIT!! semaphores initiialized\n"); /* Init Mutex to one */ seminfo.val = 1; semctlChecked(semID, SEM_PCOWSINGROUP, SETVAL, seminfo); semctlChecked(semID, SEM_PSHEEPINGROUP, SETVAL, seminfo); semctlChecked(semID, SEM_PMEALWAITINGFLAG, SETVAL, seminfo); semctlChecked(semID, SEM_PCOWSEATEN, SETVAL, seminfo); semctlChecked(semID, SEM_PSHEEPEATEN, SETVAL, seminfo); semctlChecked(semID, SEM_PTERMINATE, SETVAL, seminfo); printf("!!INIT!!INIT!!INIT!! mutexes initiialized\n"); /* Now we create and attach the segments of shared memory*/ if ((terminateFlag = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666)) < 0) { printf("!!INIT!!INIT!!INIT!! shm not created for terminateFlag\n"); exit(1); } else { printf("!!INIT!!INIT!!INIT!! shm created for terminateFlag\n"); } if ((cowCounter = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666)) < 0) { printf("!!INIT!!INIT!!INIT!! shm not created for cowCounter\n"); exit(1); } else { printf("!!INIT!!INIT!!INIT!! shm created for cowCounter\n"); } if ((sheepCounter = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666)) < 0) { printf("!!INIT!!INIT!!INIT!! shm not created for sheepCounter\n"); exit(1); } else { printf("!!INIT!!INIT!!INIT!! shm created for sheepCounter\n"); } if ((mealWaitingFlag = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666)) < 0) { printf("!!INIT!!INIT!!INIT!! shm not created for mealWaitingFlag\n"); exit(1); } else { printf("!!INIT!!INIT!!INIT!! shm created for mealWaitingFlag\n"); } if ((cowsEatenCounter = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666)) < 0) { printf("!!INIT!!INIT!!INIT!! shm not created for cowsEatenCounter\n"); exit(1); } else { printf("!!INIT!!INIT!!INIT!! shm created for cowsEatenCounter\n"); } if ((sheepEatenCounter = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666)) < 0) { printf("!!INIT!!INIT!!INIT!! shm not created for sheepEatenCounter\n"); exit(1); } else { printf("!!INIT!!INIT!!INIT!! shm created for sheepEatenCounter\n"); } /* Now we attach the segment to our data space. */ if ((terminateFlagp = shmat(terminateFlag, NULL, 0)) == (int *)-1) { printf("!!INIT!!INIT!!INIT!! shm not attached for terminateFlag\n"); exit(1); } else { printf("!!INIT!!INIT!!INIT!! shm attached for terminateFlag\n"); } if ((cowCounterp = shmat(cowCounter, NULL, 0)) == (int *)-1) { printf("!!INIT!!INIT!!INIT!! shm not attached for cowCounter\n"); exit(1); } else { printf("!!INIT!!INIT!!INIT!! shm attached for cowCounter\n"); } if ((sheepCounterp = shmat(sheepCounter, NULL, 0)) == (int *)-1) { printf("!!INIT!!INIT!!INIT!! shm not attached for sheepCounter\n"); exit(1); } else { printf("!!INIT!!INIT!!INIT!! shm attached for sheepCounter\n"); } if ((mealWaitingFlagp = shmat(mealWaitingFlag, NULL, 0)) == (int *)-1) { printf("!!INIT!!INIT!!INIT!! shm not attached for mealWaitingFlag\n"); exit(1); } else { printf("!!INIT!!INIT!!INIT!! shm attached for mealWaitingFlag\n"); } if ((cowsEatenCounterp = shmat(cowsEatenCounter, NULL, 0)) == (int *)-1) { printf("!!INIT!!INIT!!INIT!! shm not attached for cowsEatenCounter\n"); exit(1); } else { printf("!!INIT!!INIT!!INIT!! shm attached for cowsEatenCounter\n"); } if ((sheepEatenCounterp = shmat(sheepEatenCounter, NULL, 0)) == (int *)-1) { printf("!!INIT!!INIT!!INIT!! shm not attached for sheepEatenCounter\n"); exit(1); } else { printf("!!INIT!!INIT!!INIT!! shm attached for sheepEatenCounter\n"); } printf("!!INIT!!INIT!!INIT!! initialize end\n"); }
/****************************************************************//** Allocates large pages memory. @return allocated memory */ UNIV_INTERN void* os_mem_alloc_large( /*===============*/ ulint* n) /*!< in/out: number of bytes */ { void* ptr; ulint size; #if defined HAVE_LARGE_PAGES && defined UNIV_LINUX int shmid; struct shmid_ds buf; if (!os_use_large_pages || !os_large_page_size) { goto skip; } /* Align block size to os_large_page_size */ ut_ad(ut_is_2pow(os_large_page_size)); size = ut_2pow_round(*n + (os_large_page_size - 1), os_large_page_size); shmid = shmget(IPC_PRIVATE, (size_t)size, SHM_HUGETLB | SHM_R | SHM_W); if (shmid < 0) { fprintf(stderr, "InnoDB: HugeTLB: Warning: Failed to allocate" " %lu bytes. errno %d\n", size, errno); ptr = NULL; } else { ptr = shmat(shmid, NULL, 0); if (ptr == (void *)-1) { fprintf(stderr, "InnoDB: HugeTLB: Warning: Failed to" " attach shared memory segment, errno %d\n", errno); ptr = NULL; } /* Remove the shared memory segment so that it will be automatically freed after memory is detached or process exits */ shmctl(shmid, IPC_RMID, &buf); } if (ptr) { *n = size; os_fast_mutex_lock(&ut_list_mutex); ut_total_allocated_memory += size; os_fast_mutex_unlock(&ut_list_mutex); # ifdef UNIV_SET_MEM_TO_ZERO memset(ptr, '\0', size); # endif UNIV_MEM_ALLOC(ptr, size); return(ptr); } fprintf(stderr, "InnoDB HugeTLB: Warning: Using conventional" " memory pool\n"); skip: #endif /* HAVE_LARGE_PAGES && UNIV_LINUX */ #ifdef __WIN__ SYSTEM_INFO system_info; GetSystemInfo(&system_info); /* Align block size to system page size */ ut_ad(ut_is_2pow(system_info.dwPageSize)); /* system_info.dwPageSize is only 32-bit. Casting to ulint is required on 64-bit Windows. */ size = *n = ut_2pow_round(*n + (system_info.dwPageSize - 1), (ulint) system_info.dwPageSize); ptr = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (!ptr) { fprintf(stderr, "InnoDB: VirtualAlloc(%lu bytes) failed;" " Windows error %lu\n", (ulong) size, (ulong) GetLastError()); } else { os_fast_mutex_lock(&ut_list_mutex); ut_total_allocated_memory += size; os_fast_mutex_unlock(&ut_list_mutex); UNIV_MEM_ALLOC(ptr, size); } #elif !defined OS_MAP_ANON size = *n; ptr = ut_malloc_low(size, TRUE, FALSE); #else # ifdef HAVE_GETPAGESIZE size = getpagesize(); # else size = UNIV_PAGE_SIZE; # endif /* Align block size to system page size */ ut_ad(ut_is_2pow(size)); size = *n = ut_2pow_round(*n + (size - 1), size); ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | OS_MAP_ANON, -1, 0); if (UNIV_UNLIKELY(ptr == (void*) -1)) { fprintf(stderr, "InnoDB: mmap(%lu bytes) failed;" " errno %lu\n", (ulong) size, (ulong) errno); ptr = NULL; } else { os_fast_mutex_lock(&ut_list_mutex); ut_total_allocated_memory += size; os_fast_mutex_unlock(&ut_list_mutex); UNIV_MEM_ALLOC(ptr, size); } #endif return(ptr); }