sem_t * semcompat_new( int pshared, unsigned int value) { sem_t * ret; int errno_save; if (pthread_once(&support_unnamed_initialized, initialize_support_unnamed) != 0) { // errno is set by pthread_once return SEM_FAILED; } if (support_unnamed) { ret = malloc(sizeof(sem_t)); if (ret == NULL) { // errno is set by malloc return SEM_FAILED; } if (sem_init(ret, pshared, value) != 0) { errno_save = errno; free(ret); errno = errno_save; return SEM_FAILED; } return ret; } else { size_t i; char name[SEM_NAME_SIZE]; for (i = 0; i < SEM_OPEN_MAX_TRIES; ++i) { make_sem_name(name); ret = sem_open(name, O_CREAT | O_EXCL, 0600, value); if (ret == SEM_FAILED) { if (errno == EEXIST) { // try another name continue; } else { // errno is set by sem_open return SEM_FAILED; } } else { // Now that it's open, we don't want any other processes to // access it by name. if (sem_unlink(name) != 0) { LOG(LOG_WARNING, "failed to unlink semaphore %s, continuing anyway", name); } return ret; } } LOG(LOG_ERR, "failed to create a semaphore after %d tries", SEM_OPEN_MAX_TRIES); errno = EAGAIN; return SEM_FAILED; } }
/* * pj_sem_create() */ PJ_DEF(pj_status_t) pj_sem_create( pj_pool_t *pool, const char *name, unsigned initial, unsigned max, pj_sem_t **ptr_sem) { #if PJ_HAS_THREADS pj_sem_t *sem; PJ_CHECK_STACK(); PJ_ASSERT_RETURN(pool != NULL && ptr_sem != NULL, PJ_EINVAL); sem = PJ_POOL_ALLOC_T(pool, pj_sem_t); PJ_ASSERT_RETURN(sem, PJ_ENOMEM); #if defined(PJ_DARWINOS) && PJ_DARWINOS!=0 /* MacOS X doesn't support anonymous semaphore */ { char sem_name[PJ_GUID_MAX_LENGTH+1]; pj_str_t nam; /* We should use SEM_NAME_LEN, but this doesn't seem to be * declared anywhere? The value here is just from trial and error * to get the longest name supported. */ # define MAX_SEM_NAME_LEN 23 /* Create a unique name for the semaphore. */ if (PJ_GUID_STRING_LENGTH <= MAX_SEM_NAME_LEN) { nam.ptr = sem_name; pj_generate_unique_string(&nam); sem_name[nam.slen] = '\0'; } else { pj_create_random_string(sem_name, MAX_SEM_NAME_LEN); sem_name[MAX_SEM_NAME_LEN] = '\0'; } /* Create semaphore */ sem->sem = sem_open(sem_name, O_CREAT|O_EXCL, S_IRUSR|S_IWUSR, initial); if (sem->sem == SEM_FAILED) return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); /* And immediately release the name as we don't need it */ sem_unlink(sem_name); } #else sem->sem = PJ_POOL_ALLOC_T(pool, sem_t); if (sem_init( sem->sem, 0, initial) != 0) return PJ_RETURN_OS_ERROR(pj_get_native_os_error()); #endif /* Set name. */ if (!name) { name = "sem%p"; } if (strchr(name, '%')) { pj_ansi_snprintf(sem->obj_name, PJ_MAX_OBJ_NAME, name, sem); } else { strncpy(sem->obj_name, name, PJ_MAX_OBJ_NAME); sem->obj_name[PJ_MAX_OBJ_NAME-1] = '\0'; } PJ_LOG(6, (sem->obj_name, "Semaphore created")); *ptr_sem = sem; return PJ_SUCCESS; #else *ptr_sem = (pj_sem_t*)1; return PJ_SUCCESS; #endif }
WELS_THREAD_ERROR_CODE WelsEventClose (WELS_EVENT* event, str_t* event_name) { WELS_THREAD_ERROR_CODE err = sem_close (event); // match with sem_open if (event_name) sem_unlink (event_name); return err; }
void exit_fun() { shm_unlink(MEM_NAME); sem_close(sem); sem_unlink(SEM_NAME); }
system_layer2_multithreaded_callback::~system_layer2_multithreaded_callback() { sem_unlink("/waiting_sem"); sem_unlink("/shutdown_sem"); }
void nsem_test(void) { pthread_t peer = (pthread_t)0; #ifdef SDCC pthread_addr_t result; #endif FAR sem_t *sem1; FAR sem_t *sem2; struct sched_param sparam; int prio_min; int prio_max; int prio_mid; pthread_attr_t attr; int status; /* Open semaphore 2. We will create that one */ printf("nsem_test: Create semaphore 1 with value == 0\n"); sem1 = sem_open(SEM1_NAME, O_CREAT | O_EXCL, 0644, 0); if (sem1 == (FAR sem_t *)ERROR) { int errcode = errno; printf("nsem_peer: ERROR: sem_open(1) failed: %d\n", errcode); return; } /* Start the peer thread */ printf("nsem_test: Starting peer peer\n"); status = pthread_attr_init(&attr); if (status != OK) { printf("nsem_test: pthread_attr_init failed, status=%d\n", status); } prio_min = sched_get_priority_min(SCHED_FIFO); prio_max = sched_get_priority_max(SCHED_FIFO); prio_mid = (prio_min + prio_max) / 2; sparam.sched_priority = (prio_mid + prio_max) / 2; status = pthread_attr_setschedparam(&attr, &sparam); if (status != OK) { printf("nsem_test: ERROR: pthread_attr_setschedparam failed, status=%d\n", status); } else { printf("nsem_test: Set peer priority to %d\n", sparam.sched_priority); } status = pthread_create(&peer, &attr, nsem_peer, NULL); if (status != 0) { printf("nsem_test: ERROR: Peer thread creation failed: %d\n", status); return; } /* Wait for the peer to post semaphore 1 */ printf("nsem_test: Wait on semaphore 1\n"); status = sem_wait(sem1); if (status < 0) { int errcode = errno; printf("nsem_test: ERROR: sem_wait(1) failed: %d\n", errcode); pthread_cancel(peer); return; } /* Close sem1. It should already have been unlinked by the nsem_peer */ printf("nsem_test: Close semaphore 1\n"); sem_close(sem1); /* Open semaphore 2. This should have already been created by * nsem_peer(). */ printf("nsem_test: Open semaphore 2\n"); sem2 = sem_open(SEM2_NAME, 0); if (sem2 == (FAR sem_t *)ERROR) { int errcode = errno; printf("nsem_test: ERROR: sem_open(2) failed: %d\n", errcode); pthread_cancel(peer); return; } /* Wait for the peer to post semaphore 2 */ printf("nsem_test: Wait on semaphore 2\n"); status = sem_wait(sem2); if (status < 0) { int errcode = errno; printf("nsem_test: ERROR: sem_wait(1) failed: %d\n", errcode); pthread_cancel(peer); return; } /* Close and unlink semaphore 2 */ printf("nsem_test: Close and unlink semaphore 2\n"); sem_close(sem2); sem_unlink(SEM2_NAME); #ifdef SDCC if (peer != (pthread_t)0) { pthread_join(peer, &result); } #else if (peer != (pthread_t)0) { pthread_join(peer, NULL); } #endif }
IPC *ipc_open(int semflags, int memflags) { IPC *ipp = malloc(sizeof(IPC)); memset(ipp, 0, sizeof(IPC)); char buf[4096]; int written_len = 0; // FILE *log = stdout; //fprintf(log, "logging\n"); if (semflags & O_CREAT) { sem_unlink(SEM_NAME "CALLER"); sem_unlink(SEM_NAME "SERVER"); sem_unlink(SEM_NAME "REPLY"); ipp->mutex_caller = sem_open(SEM_NAME "CALLER", semflags, 0666, 1); ipp->mutex_server = sem_open(SEM_NAME "SERVER", semflags, 0666, 0); ipp->mutex_reply = sem_open(SEM_NAME "REPLY", semflags, 0666, 0); } else { ipp->mutex_caller = sem_open(SEM_NAME "CALLER", semflags); ipp->mutex_server = sem_open(SEM_NAME "SERVER", semflags); ipp->mutex_reply = sem_open(SEM_NAME "REPLY", semflags); } if (ipp->mutex_caller == SEM_FAILED || ipp->mutex_server == SEM_FAILED || ipp->mutex_reply == SEM_FAILED) { error("Open semaphore failed: %s: %s\n", SEM_NAME, strerror(errno)); goto sem_fail; } ipp->fd = open(SHM_PATH, memflags | O_RDWR, 0600); if (ipp->fd < 0) { error("Error opening shared file: %s: %s\n", SHM_PATH, strerror(errno)); goto sem_fail; } if (memflags & O_CREAT) { memset(buf, 0, sizeof(buf)); while (written_len < SHM_SIZ) { write(ipp->fd, buf, sizeof(buf)); written_len += sizeof(buf); } } lseek(ipp->fd, 0, SEEK_SET); ipp->shm = mmap(NULL, SHM_SIZ, PROT_READ | PROT_WRITE, MAP_SHARED, ipp->fd, 0); if (ipp->shm == MAP_FAILED) { error("mmap: %s\n", strerror(errno)); goto sem_fail; } close(ipp->fd); ipp->dbid = 0; return ipp; sem_fail: //fprintf(log, "FAILURE CONDITION\n"); free(ipp); //fprintf(log, "DONE\n"); /* SEM_DESTROY(ipp->mutex_caller, "CALLER") */ /* SEM_DESTROY(ipp->mutex_server, "SERVER") */ /* SEM_DESTROY(ipp->mutex_reply, "REPLY") */ // fclose(log); return NULL; }
int main(int argc, char *argv[]) { if(argc != 2) { fprintf(stderr, "Use this program with the argument 'port'.\n"); exit(EXIT_FAILURE); } char *endptr = NULL; long int port = strtol(argv[1], &endptr, 10); if((port == LONG_MAX || port == LONG_MIN) && errno == ERANGE) { perror("strtol"); exit(EXIT_FAILURE); } if(argv[1] == endptr) { fprintf(stderr, "Error: no digits were found.\n"); exit(EXIT_FAILURE); } if(port <= 0 || port > 65535) { fprintf(stderr, "Error: %ld isn't a number of port.\n", port); exit(EXIT_FAILURE); } printf("Enter the count of landing planes: "); size_t n; if(scanf("%lu", &n) < 1) { perror("scanf"); exit(EXIT_FAILURE); } printf("Enter the number of departing planes: "); size_t m; if(scanf("%lu", &m) < 1) { perror("scanf"); exit(EXIT_FAILURE); } printf("Enter the number of strips: "); size_t k; if(scanf("%lu", &k) < 1) { perror("scanf"); exit(EXIT_FAILURE); } sem_t **sems; sems = (sem_t **)malloc(sizeof(sem_t *) * k); if(sems == NULL) { perror("malloc"); exit(EXIT_FAILURE); } for(size_t i = 0; i < k; ++i) { char tmp[25]; if(snprintf(tmp, 25, SEM_NAME, i) <= 0) { perror("snprintf"); free(sems); exit(EXIT_FAILURE); } if((sems[i] = sem_open(tmp, O_CREAT, 0666, 0)) == SEM_FAILED) { perror("sem_open"); free(sems); exit(EXIT_FAILURE); } while(sem_trywait(sems[i]) == 0) {} if(errno != EAGAIN) { perror("sem_trywait"); for(size_t j = i; j > 0; --j) { snprintf(tmp, 25, SEM_NAME, j); sem_unlink(tmp); } free(sems); exit(EXIT_FAILURE); } if(sem_post(sems[i]) != 0) { perror("sem_open"); for(size_t j = i; j > 0; --j) { snprintf(tmp, 25, SEM_NAME, j); sem_unlink(tmp); } free(sems); exit(EXIT_FAILURE); } } struct sockaddr_in servaddr; int sockfd, newsockfd; if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket"); for(size_t j = 0; j < k; ++j) { char tmp[25]; snprintf(tmp, 25, SEM_NAME, j); sem_unlink(tmp); } free(sems); exit(EXIT_FAILURE); } bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { perror("bind"); for(size_t j = 0; j < k; ++j) { char tmp[25]; snprintf(tmp, 25, SEM_NAME, j); sem_unlink(tmp); } free(sems); close(sockfd); exit(EXIT_FAILURE); } if(listen(sockfd, n + m + 1) < 0) { perror("listen"); for(size_t j = 0; j < k; ++j) { char tmp[25]; snprintf(tmp, 25, SEM_NAME, j); sem_unlink(tmp); } free(sems); close(sockfd); exit(EXIT_FAILURE); } size_t num_of_next_strip = 0; while(1) { if((newsockfd = accept(sockfd, NULL, NULL)) < 0) { perror("accept"); for(size_t j = 0; j < k; ++j) { char tmp[25]; snprintf(tmp, 25, SEM_NAME, j); sem_unlink(tmp); } free(sems); close(sockfd); exit(EXIT_FAILURE); } char status; if(read(newsockfd, &status, 1) <= 0) { perror("read"); for(size_t j = 0; j < k; ++j) { char tmp[25]; snprintf(tmp, 25, SEM_NAME, j); sem_unlink(tmp); } free(sems); close(sockfd); exit(EXIT_FAILURE); } if(status == 0) { printf("We received a request for landing.\n"); } else { printf("We received a request for departure.\n"); } int pid = fork(); if(pid < 0) { perror("fork"); for(size_t j = 0; j < k; ++j) { char tmp[25]; snprintf(tmp, 25, SEM_NAME, j); sem_unlink(tmp); } free(sems); close(sockfd); exit(EXIT_FAILURE); } else if(pid == 0) { sem_t *my_sem = sems[num_of_next_strip]; free(sems); close(sockfd); char c = 0; if(write(newsockfd, &c, 1) <= 0) { perror("write"); exit(EXIT_FAILURE); } if(sem_wait(my_sem) != 0) { perror("sem_wait"); exit(EXIT_FAILURE); } printf("Stip number %lu is busy.\n", num_of_next_strip + 1); ++num_of_next_strip; if(write(newsockfd, &num_of_next_strip, sizeof(size_t)) <= 0) { close(newsockfd); fprintf(stderr, "We can not establish a connection.\n"); exit(EXIT_FAILURE); } --num_of_next_strip; char ansv; if(read(newsockfd, &ansv, 1) <= 0) { close(newsockfd); fprintf(stderr, "We can not establish a connection.\n"); exit(EXIT_FAILURE); } if(ansv == 0) printf("Strip number %lu is free.\n", num_of_next_strip + 1); close(newsockfd); if(sem_post(my_sem) != 0) { close(newsockfd); fprintf(stderr, "The accident on the strip %lu.\n", num_of_next_strip + 1); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } ++num_of_next_strip; if(num_of_next_strip == k) num_of_next_strip = 0; close(newsockfd); } }
int main(int argc, char *argv[]) { mutex = sem_open("/mutex", O_CREAT, 0644, 1); fillSlots = sem_open("/fillSlots", O_CREAT, 0644, 0); emptySlots = sem_open("/emptySlots", O_CREAT, 0644, N); // Two necessary calls to allocate the shared memory space SHM_SIZE = 3 * sizeof(int) + N * sizeof(int); shmid = shmget(shmkey, SHM_SIZE, 0666 | IPC_CREAT); // IPC_CREAT flag to create shared mem int *shmpointer = shmat(shmid,NULL,0); //now attach a memory to this share memory if(shmid < 0 || shmpointer == NULL) { printf("error allocating shared memory key %d\n", shmkey); return -1; } shmpointer[0] = 0; // in shmpointer[1] = 0; // out shmpointer[2] = 1; // last item produced printf("*** FactoryShell Usage **** \n"); printf("FactoryShell> producer 3 (type this to produce 3 items)\n"); printf("FactoryShell> consumer 4 (type this to consume 4 items,\n"); printf(" 3 will be consumed and then block)\n"); printf("Return or end to quit\n"); while(!bEnd) { printf("FactoryShell> "); fgets(cmd, sizeof(cmd), stdin); strcpy(arg,""); if (strchr(cmd, ' ') != NULL) sscanf(cmd,"%s %s",role,arg); else sscanf(cmd,"%s",role); if(strcmp(role,"end") == 0 || strcmp(role, "exit")==0) { bEnd = 1; break; } //fill the args we will pass to the child programs getcwd(programpath, 80); strcat(programpath, "/"); strcat(programpath, role); args[0] = programpath; args[1] = arg; args[2] = Nstr; args[3] = NULL; if(strcmp(role,"consumer") == 0 || strcmp(role, "producer") == 0) { // ********************************************************************** // Exercice) Add the necessary code here to call the children pid = fork(); if(pid==0) { execve(programpath, args, NULL); } else if(pid<0) { printf("Error when forking the program\n"); bEnd = 1; } } else { printf("Command not recognized\n"); printf("Usage: producer integer (num of elems to produce)\n"); printf(" consumer integer (num of elems to consume)\n\n"); if(strlen(cmd) == 1) bEnd = 1; } usleep(1000000); } shmdt(shmpointer); shmctl(shmid, IPC_RMID, 0); sem_close(mutex); sem_close(fillSlots); sem_close(emptySlots); sem_unlink("/mutex"); sem_unlink("/fillSlots"); sem_unlink("/emptySlots"); return 0; }
int main(int argc, char *argv[]) { sem_t *sem_mutex; //Binary semaphore to use a mutex int *stateptr; //Shared memory global int to store active button state int hit_count = 0, rows, cols; WINDOW *mainwin = NULL; int nextch; MEVENT event; struct sigaction act; //Create a binary semaphore to use as a mutex: //(will be inerited by children) if ((sem_mutex = sem_open("/mutex", O_CREAT|O_EXCL, 0600, 1)) == SEM_FAILED) { perror("Semaphore creation failed"); return EXIT_FAILURE; } //Now unlink semaphore so it will be deleted in case of ^-C or crash: sem_unlink("/mutex"); //Setup anonymous, shared memory for global int: if ((stateptr = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0)) == MAP_FAILED) { perror("Shared memory creation failed"); return EXIT_FAILURE; } //Initialize button state (no active buttons): *stateptr = 0; //Initialize and setup the curses window: if ((mainwin = initscr()) == NULL) { fprintf(stderr,"Failed to initialize curses window\n"); return EXIT_FAILURE; } getmaxyx(mainwin,rows,cols); mvprintw(rows/2,cols/2-18,"Click on the Corner Buttons to Score!",rows,cols); mvprintw(rows/2+2,cols/2-10,"(rows: %d cols: %d)",rows,cols); refresh(); //Setup signal handler for SIGCHLD signals: memset(&act,0,sizeof(act)); act.sa_handler = sigchld_handler; sigemptyset(&act.sa_mask); sigaction(SIGCHLD,&act,NULL); //Create children: //**************** for (int i=0; i < running; i++){//memory problem??? switch(fork()){ case -1: perror("fork failed"); sigchld_handler(EXIT_FAILURE); endwin();//put this in here since failures don't close the window apparently. exit(EXIT_FAILURE); case 0: child_func(1+i, rows, cols,sem_mutex,stateptr);//1+processcount allows for proper numbering. sigchld_handler(EXIT_SUCCESS); exit(EXIT_SUCCESS); default: break;//no break leads to error apparently. //I got it now the switch statement will determine the parent function follows the default. } } //Setup curses to get mouse events: keypad(mainwin, TRUE); mousemask(ALL_MOUSE_EVENTS, NULL); //Loop catching mouse clicks while children are running: while (running > 0) { //nextch = wgetch(mainwin); if ((nextch = getch()) == KEY_MOUSE && getmouse(&event) == OK && (event.bstate & BUTTON1_PRESSED)) { //Check if user clicked on a label: if (check_click(*stateptr, event.x, event.y, rows, cols)) { //Clicked on current label: hit_count++; mvprintw(rows/2+5,cols/2-11,"Got #%d at (%3d,%3d)",*stateptr,event.x,event.y); wrefresh(curscr); //Need this to ensure entire screen is redrawn despite child changes. } } } //Close curses window so terminal settings are restored to normal: endwin(); //Print out results: printf("\nYour hit count was: %d\n\n",hit_count); //Collect all the children: //************************* //return exit success if child successfully exited. int status; int tempcount = 0;//made a temp count since I think running will be 0 by now. while(tempcount<4){ wait(&status);// wait for children shouldn't all return status if(WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS){ tempcount++;//increment temp count. }else exit(EXIT_FAILURE);//return exit failure according to lecture. } exit(EXIT_SUCCESS);//completes while loop so returns exit success. }
/* The main test function. */ int main(int argc, char *argv[]) { int ret, value; sem_t *sem1, *sem2; /* Initialize output */ output_init(); /* Create the semaphore */ sem1 = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0777, 1); if ((sem1 == SEM_FAILED) && (errno == EEXIST)) { sem_unlink(SEM_NAME); sem1 = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0777, 1); } if (sem1 == SEM_FAILED) { UNRESOLVED(errno, "Failed to create the semaphore"); } /* Unlink */ ret = sem_unlink(SEM_NAME); if (ret != 0) { UNRESOLVED(errno, "Failed to unlink the semaphore"); } /* Try reconnect */ sem2 = sem_open(SEM_NAME, 0); if (sem2 != SEM_FAILED) { FAILED("Reconnecting the unlinked semaphore did not failed"); } if (errno != ENOENT) { output("Error %d: %s\n", errno, strerror(errno)); FAILED ("Reconnecting the unlinked semaphore failed with a wrong error"); } /* Reopen the semaphore */ sem2 = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0777, 3); if (sem2 == SEM_FAILED) { output("Gor error %d: %s\n", errno, strerror(errno)); FAILED("Failed to recreate the semaphore"); } /* Check the semaphore have different values */ ret = sem_getvalue(sem1, &value); if (ret != 0) { UNRESOLVED(errno, "Failed to read sem1 value"); } if (value != 1) { output("Read: %d\n", value); FAILED("Semaphore value is not as expected"); } ret = sem_getvalue(sem2, &value); if (ret != 0) { UNRESOLVED(errno, "Failed to read sem1 value"); } if (value != 3) { output("Read: %d\n", value); FAILED("Semaphore value is not as expected"); } /* Unlink */ ret = sem_unlink(SEM_NAME); if (ret != 0) { UNRESOLVED(errno, "Failed to unlink the semaphore"); } /* close both */ ret = sem_close(sem1); if (ret != 0) { UNRESOLVED(errno, "Failed to close the semaphore"); } ret = sem_close(sem2); if (ret != 0) { UNRESOLVED(errno, "Failed to close the semaphore"); } /* Test passed */ #if VERBOSE > 0 output("Test passed\n"); #endif PASSED; }
int mca_sharedfp_sm_file_open (struct ompi_communicator_t *comm, char* filename, int amode, struct ompi_info_t *info, mca_io_ompio_file_t *fh) { int err = OMPI_SUCCESS; struct mca_sharedfp_base_data_t* sh; struct mca_sharedfp_sm_data * sm_data = NULL; mca_io_ompio_file_t * shfileHandle; char * filename_basename; char * sm_filename; struct sm_offset * sm_offset_ptr; struct sm_offset sm_offset; int sm_fd; int rank; /*----------------------------------------------------*/ /*Open the same file again without shared file pointer*/ /*----------------------------------------------------*/ shfileHandle = (mca_io_ompio_file_t *)malloc(sizeof(mca_io_ompio_file_t)); err = ompio_io_ompio_file_open(comm,filename,amode,info,shfileHandle,false); if ( OMPI_SUCCESS != err) { opal_output(0, "mca_sharedfp_sm_file_open: Error during file open\n"); return err; } /*Memory is allocated here for the sh structure*/ if ( mca_sharedfp_sm_verbose ) { printf( "mca_sharedfp_sm_file_open: malloc f_sharedfp_ptr struct\n"); } sh = (struct mca_sharedfp_base_data_t*)malloc(sizeof(struct mca_sharedfp_base_data_t)); if ( NULL == sh ) { opal_output(0, "mca_sharedfp_sm_file_open: Error, unable to malloc f_sharedfp_ptr struct\n"); free(shfileHandle); return OMPI_ERR_OUT_OF_RESOURCE; } /*Populate the sh file structure based on the implementation*/ sh->sharedfh = shfileHandle; /* Shared file pointer*/ sh->global_offset = 0; /* Global Offset*/ sh->comm = comm; /* Communicator*/ sh->selected_module_data = NULL; rank = ompi_comm_rank ( sh->comm ); /*Open a shared memory segment which will hold the shared file pointer*/ if ( mca_sharedfp_sm_verbose ) { printf( "mca_sharedfp_sm_file_open: allocatge shared memory segment.\n"); } sm_data = (struct mca_sharedfp_sm_data*) malloc ( sizeof(struct mca_sharedfp_sm_data)); if ( NULL == sm_data ){ opal_output(0, "mca_sharedfp_sm_file_open: Error, unable to malloc sm_data struct\n"); free(sh); free(shfileHandle); return OMPI_ERR_OUT_OF_RESOURCE; } sm_data->sm_filename=NULL; /* the shared memory segment is identified opening a file ** and then mapping it to memory ** For sharedfp we also want to put the file backed shared memory into the tmp directory ** TODO: properly name the file so that different jobs can run on the same system w/o ** overwriting each other, e.g. orte_process_info.proc_session_dir */ /*sprintf(sm_filename,"%s%s",filename,".sm");*/ filename_basename = basename(filename); sm_filename = (char*) malloc( sizeof(char) * (strlen(filename_basename)+64) ); if (NULL == sm_filename) { free(sm_data); free(sh); free(shfileHandle); return OMPI_ERR_OUT_OF_RESOURCE; } sprintf(sm_filename,"/tmp/OMPIO_sharedfp_sm_%s%s",filename_basename,".sm"); /* open shared memory file, initialize to 0, map into memory */ sm_fd = open(sm_filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if ( sm_fd == -1){ /*error opening file*/ printf("mca_sharedfp_sm_file_open: Error, unable to open file for mmap: %s\n",sm_filename); free(sm_filename); free(sm_data); free(sh); free(shfileHandle); return OMPI_ERROR; } free(sm_filename); sm_data->sm_filename = sm_filename; /*TODO: is it necessary to write to the file first?*/ if( 0 == rank ){ memset ( &sm_offset, 0, sizeof (struct sm_offset )); write ( sm_fd, &sm_offset, sizeof(struct sm_offset)); } comm->c_coll.coll_barrier (comm, comm->c_coll.coll_barrier_module ); /*the file has been written to, now we can map*/ sm_offset_ptr = mmap(NULL, sizeof(struct sm_offset), PROT_READ | PROT_WRITE, MAP_SHARED, sm_fd, 0); close(sm_fd); if ( sm_offset_ptr==MAP_FAILED){ err = OMPI_ERROR; printf("mca_sharedfp_sm_file_open: Error, unable to mmap file: %s\n",sm_filename); printf("%s\n", strerror(errno)); free(sm_filename); free(sm_data); free(sh); free(shfileHandle); return OMPI_ERROR; } /* Initialize semaphore so that is shared between processes. */ /* the semaphore is shared by keeping it in the shared memory segment */ #ifdef OMPIO_SHAREDFP_USE_UNNAMED_SEMAPHORES if(sem_init(&sm_offset_ptr->mutex, 1, 1) != -1){ #else sm_data->sem_name = (char*) malloc( sizeof(char) * (strlen(filename_basename)+32) ); sprintf(sm_data->sem_name,"OMPIO_sharedfp_sem_%s",filename_basename); if( (sm_data->mutex = sem_open(sm_data->sem_name, O_CREAT, 0644, 1)) != SEM_FAILED ) { #endif /*If opening was successful*/ /*Store the new file handle*/ sm_data->sm_offset_ptr = sm_offset_ptr; /* Assign the sm_data to sh->selected_module_data*/ sh->selected_module_data = sm_data; /*remember the shared file handle*/ fh->f_sharedfp_data = sh; /*write initial zero*/ if(rank==0){ MPI_Offset position=0; #ifdef OMPIO_SHAREDFP_USE_UNNAMED_SEMAPHORES sem_wait(sm_offset_ptr->mutex); sm_offset_ptr->offset=position; sem_post(sm_offset_ptr->mutex); #else sem_wait(sm_data->mutex); sm_offset_ptr->offset=position; sem_post(sm_data->mutex); #endif } }else{ free(sm_filename); free(sm_data); free(sh); free(shfileHandle); munmap(sm_offset_ptr, sizeof(struct sm_offset)); err = OMPI_ERROR; } comm->c_coll.coll_barrier (comm, comm->c_coll.coll_barrier_module ); return err; } int mca_sharedfp_sm_file_close (mca_io_ompio_file_t *fh) { int err = OMPI_SUCCESS; /*sharedfp data structure*/ struct mca_sharedfp_base_data_t *sh=NULL; /*sharedfp sm module data structure*/ struct mca_sharedfp_sm_data * file_data=NULL; if( NULL == fh->f_sharedfp_data ){ if ( mca_sharedfp_sm_verbose ) { printf("sharedfp_sm_file_close: shared file pointer structure not initialized\n"); } return OMPI_SUCCESS; } sh = fh->f_sharedfp_data; /* Use an MPI Barrier in order to make sure that * all processes are ready to release the * shared file pointer resources */ sh->comm->c_coll.coll_barrier (sh->comm, sh->comm->c_coll.coll_barrier_module ); file_data = (sm_data*)(sh->selected_module_data); if (file_data) { /*Close sm handle*/ if (file_data->sm_offset_ptr) { /* destroy semaphore */ #ifdef OMPIO_SHAREDFP_USE_UNNAMED_SEMAPHORES sem_destroy(file_data->sm_offset_ptr->mutex); #else sem_unlink (file_data->sem_name); free (file_data->sem_name); #endif /*Release the shared memory segment.*/ munmap(file_data->sm_offset_ptr,sizeof(struct sm_offset)); /*Q: Do we need to delete the file? */ remove(file_data->sm_filename); } /*free our sm data structure*/ if(file_data->sm_filename){ free(file_data->sm_filename); } free(file_data); } /* Close the main file opened by this component*/ err = ompio_io_ompio_file_close(sh->sharedfh); /*free shared file pointer data struct*/ free(sh); return err; }
/* The main test function. */ int main(void) { int ret, i; char *name = "/sem_open_15_1"; sem_t *sems[4]; /* Initialize output */ output_init(); /* Initialize all semaphores */ for (i = 0; i < 4; i++) { sems[i] = sem_open(name, O_CREAT, 0777, 1); if (sems[i] == SEM_FAILED) { UNRESOLVED(errno, "Failed to sem_open"); } } /* Check all calls returned the same @ */ for (i = 0; i < 3; i++) { if (sems[i] != sems[i + 1]) { FAILED("sem_open returned a different address"); } /* Close some semaphores */ ret = sem_close(sems[i]); if (ret != 0) { UNRESOLVED(errno, "Failed to sem_close"); } } /* Now, reopen, we should still get the same address */ for (i = 0; i < 3; i++) { sems[i] = sem_open(name, O_CREAT, 0777, 1); if (sems[i] == SEM_FAILED) { UNRESOLVED(errno, "Failed to sem_open"); } } /* Check all calls returned the same @ */ for (i = 0; i < 3; i++) { if (sems[i] != sems[i + 1]) { FAILED("sem_open returned a different address"); } } /* Close all semaphores */ for (i = 0; i < 4; i++) { ret = sem_close(sems[i]); if (ret != 0) { UNRESOLVED(errno, "Failed to sem_close"); } } sem_unlink(name); /* Test passed */ #if VERBOSE > 0 output("Test passed\n"); #endif PASSED; }
int main(){ char *array; int fd; sem_t *sema_n; int ret,val; printf("%s : Im start \n", MYNAME); char pathname[] = "lab901.c"; /* Получаем дескриптор общей памяти */ sem_getvalue(sema_n, &val); printf("semaphore value = %d\n", val); if ((shm_fd = shm_open("my_shm", O_CREAT | O_RDWR, 0666)) == -1){ perror("cannot open"); return -1; } /* Устанавливаем размер общей памяти равным SHM_SIZE */ if (ftruncate(shm_fd, SHM_SIZE) != 0){ perror("cannot set size"); return -1; } /* * Подключаем общую память в адресное пространство. Флаг * MAP_SHARED говорит, что это подключение общей памяти. */ if ((array = (char *) mmap(0, SHM_SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0)) == MAP_FAILED){ perror("cannot mmap"); return -1; } sem_wait(sema_n); /* Блокируем общую память. Не забываем про этот шаг */ if (mlock(vaddr, SHM_SIZE) != 0){ perror("cannot mlock"); return -1; } int i; i = 0; printf("%s : code in lab901.c:\n", MYNAME); printf("-----------------------------------------------------------\n\n"); while (array[i] != EOF ){ putchar(array[i]); ++i; } printf("%s \n", array); if (sem_post(sema_n) != 0) perror("post error"); munmap(vaddr, SHM_SIZE); sem_close(sema_n); sem_unlink(SEM_NAME); close(shm_fd); shm_unlink("my_shm"); printf("%s : \nAll shared mamory released\n\n", MYNAME); return 0; }
void *POSIX_Init( void *argument ) { int status; int value; int i; sem_t sems[MAX_SEMS]; sem_t sem2; sem_t *n_sem1; sem_t *n_sem2; struct timespec waittime; char failure_msg[80]; TEST_BEGIN(); puts( "Init: sem_init - UNSUCCESSFUL (EINVAL)" ); status = sem_init(NULL, 0, 1); fatal_posix_service_status( status, -1, "sem_init error return status"); fatal_posix_service_status( errno, EINVAL, "sem_init errorno EINVAL" ); puts( "Init: sem_init - SUCCESSFUL" ); for (i = 0; i < MAX_SEMS; i++) { status = sem_init(&sems[i], 0, i); sprintf(failure_msg, "sem_init %d", i ); fatal_posix_service_status( status, 0, failure_msg); } puts( "Init: sem_init - UNSUCCESSFUL (ENOSPC)" ); status = sem_init(&sem2, 0, 1); fatal_posix_service_status( status, -1, "sem_init error return status"); fatal_posix_service_status( errno, ENOSPC, "sem_init errorno ENOSPC" ); puts( "Init: sem_init - UNSUCCESSFUL (ENOSYS -- pshared not supported)" ); status = sem_init(&sem2, 1, 1); fatal_posix_service_status( status, -1, "sem_init error return status"); fatal_posix_service_status( errno, ENOSYS, "sem_init errno set to ENOSYS"); puts( "Init: sem_getvalue - SUCCESSFUL "); for (i = 0; i < MAX_SEMS; i++) { status = sem_getvalue(&sems[i], &value); sprintf( failure_msg, "sem_getvalue %d", i ); fatal_posix_service_status( status, 0, failure_msg ); fatal_posix_service_status( value, i, "sem_getvalue correct value" ); } puts( "Init: sem_getvalue - UNSUCCESSFUL "); status = sem_getvalue(&sem2, &value); fatal_posix_service_status( status, -1, "sem_getvalue error return status"); fatal_posix_service_status( errno, EINVAL, "sem_getvalue errno EINVAL"); puts( "Init: sem_destroy - SUCCESSFUL" ); status = sem_destroy(&sems[0]); fatal_posix_service_status( status, 0, "sem_destroy semaphore 0"); puts( "Init: sem_destroy - UNSUCCESSFUL (EINVAL)" ); status = sem_destroy(&sem2); fatal_posix_service_status( status, -1, "sem_destroy error return status"); fatal_posix_service_status( errno, EINVAL, "sem_destroy errno EINVAL"); puts( "Init: sem_wait - SUCCESSFUL" ); status = sem_wait(&sems[1]); fatal_posix_service_status( status, 0, "sem_wait semaphore 1"); /* sem[1].count = 0 */ puts( "Init: sem_wait - UNSUCCESSFUL (EINVAL)" ); status = sem_wait(&sem2); fatal_posix_service_status( status, -1, "sem_wait error return status"); fatal_posix_service_status( errno, EINVAL, "sem_wait errno EINVAL"); puts( "Init: sem_post - SUCCESSFUL" ); status = sem_post(&sems[1]); fatal_posix_service_status( status, 0, "sem_post semaphore 1"); /* sem[1].count = 1 */ puts( "Init: sem_wait - SUCCESSFUL (after a sem_post)" ); status = sem_wait(&sems[1]); fatal_posix_service_status( status, 0, "sem_wait semaphore 1"); /* sem[1].count = 0 */ puts( "Init: sem_trywait - SUCCESSFUL" ); status = sem_trywait(&sems[2]); fatal_posix_service_status( status, 0, "sem_trywait semaphore 2"); /* sem[2].count = 1 */ puts( "Init: sem_trywait - UNSUCCESSFUL (EAGAIN)" ); status = sem_trywait(&sems[1]); fatal_posix_service_status( status, -1, "sem_trywait error return status"); fatal_posix_service_status( errno, EAGAIN, "sem_trywait errno EAGAIN"); /* sem[1].count = 0 */ puts( "Init: sem_trywait - UNSUCCESSFUL (EINVAL)" ); status = sem_trywait(&sem2); fatal_posix_service_status( status, -1, "sem_trywait error return status"); fatal_posix_service_status( errno, EINVAL, "sem_trywait errno EINVAL"); #if 0 status = sem_post(&sems[2]); fatal_posix_service_status( status, 0, "sem_post semaphore 2"); /* sem[2].count = 2 */ #else /* sem[2].count = 1 */ #endif puts( "Init: sem_timedwait - SUCCESSFUL" ); waittime.tv_sec = time(NULL) + 1; waittime.tv_nsec = 100; status = sem_timedwait(&sems[2], &waittime); fatal_posix_service_status( status, 0, "sem_timedwait semaphore 2"); /* sem[2].count = 0 */ puts( "Init: sem_timedwait - UNSUCCESSFUL (ETIMEDOUT)" ); status = sem_timedwait(&sems[2], &waittime); fatal_posix_service_status( status, -1, "sem_timedwait error return status"); fatal_posix_service_status( errno, ETIMEDOUT, "sem_timedwait errno ETIMEDOUT"); /* * To do this case, we must be blocking when we want the semaphore. * POSIX doesn't want you to check the error if you can get the resource. */ #if 1 puts( "Init: sem_timedwait - UNSUCCESSFUL (EINVAL) -- skipping" ); #else puts( "Init: sem_timedwait - UNSUCCESSFUL (EINVAL)" ); waittime.tv_sec = 0; waittime.tv_nsec = 0x7FFFFFFF; status = sem_timedwait(&sems[2], &waittime); fatal_posix_service_status( status, -1, "sem_timedwait error return status"); fatal_posix_service_status( errno, EINVAL, "sem_init errno EINVAL"); #endif puts( "Init: sem_post - UNSUCCESSFUL (EINVAL)" ); status = sem_post(&sem2); fatal_posix_service_status( status, -1, "sem_post error return status"); fatal_posix_service_status( errno, EINVAL, "sem_post errno EINVAL"); puts( "Init: sem_destroy - SUCCESSFUL" ); for (i = 1; i < MAX_SEMS; i++) { status = sem_destroy(&sems[i]); sprintf( failure_msg, "sem_destroy %d", i ); fatal_posix_service_status( status, 0, failure_msg ); } /* Modes are currently unsupported */ /* * Validate all sem_open return paths. */ puts( "Init: sem_open - UNSUCCESSFUL (ENAMETOOLONG)" ); n_sem1 = sem_open(Get_Too_Long_Name(), O_CREAT, 0777, 1 ); fatal_posix_sem( n_sem1, "sem_open error return status" ); fatal_posix_service_status( errno, ENAMETOOLONG, "sem_open errorno ENAMETOOLONG" ); puts( "Init: sem_open - sem1 SUCCESSFUL" ); n_sem1 = sem_open( "sem1",O_CREAT, 0777, 1 ); rtems_test_assert( n_sem1 != SEM_FAILED ); puts( "Init: sem_destroy - named sem1 - EINVAL" ); status = sem_destroy(n_sem1); fatal_posix_service_status( status, -1, "sem_destroy named semaphore"); fatal_posix_service_status( errno, EINVAL, "sem_destroy named semaphore"); puts( "Init: sem_open - Create an Existing sem (EEXIST)" ); n_sem2 = sem_open("sem1", O_CREAT | O_EXCL, 0777, 1); fatal_posix_sem( n_sem2, "sem_open error return status" ); fatal_posix_service_status( errno, EEXIST, "sem_open errno EEXIST"); puts( "Init: sem_open - Open new sem without create flag (ENOENT)" ); n_sem2 = sem_open("sem3", O_EXCL, 0777, 1); fatal_posix_sem( n_sem2, "sem_open error return status" ); fatal_posix_service_status( errno, ENOENT, "sem_open errno EEXIST"); /* * XXX - Could not hit the following errors: * E_POSIX_Semaphore_Create_support only fails if * ENOSYS - When semaphore is shared between processes. * ENOSPC - When out of memory. */ /* * Validate we can wait on a semaphore opened with sem_open. */ puts( "Init: sem_wait on sem1" ); status = sem_wait(n_sem1); fatal_posix_service_status( status, 0, "sem_wait opened semaphore"); /* * Validate a second open returns the same semaphore. */ puts( "Init: sem_open - Open an existing sem ( same id )" ); n_sem2 = sem_open("sem1", 0 ); rtems_test_assert( n_sem2 == n_sem1 ); /* * Unlink the semaphore, then verify an open of the same name produces a * different semaphore. */ puts( "Init: sem_unlink - sem1 SUCCESSFUL" ); status = sem_unlink( "sem1" ); fatal_posix_service_status( status, 0, "sem_unlink locked semaphore"); puts( "Init: sem_open - Reopen sem1 SUCCESSFUL with a different id" ); n_sem2 = sem_open( "sem1", O_CREAT | O_EXCL, 0777, 1); rtems_test_assert( n_sem2 != SEM_FAILED ); rtems_test_assert( n_sem2 != n_sem1 ); /* * Validate we can call close on a semaphore opened with sem_open. */ puts( "Init: sem_close (1) - SUCCESSFUL" ); status = sem_close( n_sem1 ); fatal_posix_service_status( status, 0, "sem_close semaphore"); /* * Validate it n_sem2 (the last open for sem1 name can be * correctly closed and unlinked. */ puts( "Init: sem_close (2) - SUCCESSFUL" ); status = sem_close( n_sem2 ); fatal_posix_service_status( status, 0, "sem_close semaphore"); puts( "Init: sem_unlink - sem1 (2) SUCCESSFUL" ); status = sem_unlink( "sem1" ); fatal_posix_service_status( status, 0, "sem_unlink locked semaphore"); puts( "Init: sem_close - UNSUCCESSFUL (EINVAL)" ); status = sem_close(n_sem2); fatal_posix_service_status( status, -1, "sem_close error return status"); fatal_posix_service_status( errno, EINVAL, "sem_close errno EINVAL"); puts( "Init: sem_unlink - UNSUCCESSFUL (ENOENT)" ); status = sem_unlink("sem1"); fatal_posix_service_status( status, -1, "sem_unlink error return status"); fatal_posix_service_status( errno, ENOENT, "sem_close errno EINVAL"); /* * Validate we can unlink (2) */ puts( "Init: sem_unlink (NULL) - EINVAL" ); status = sem_unlink( NULL ); fatal_posix_service_status( status, -1, "sem_unlink error return status"); fatal_posix_service_status( errno, EINVAL, "sem_unlink errno value"); puts( "Init: sem_unlink (\"\") - EINVAL" ); status = sem_unlink( "" ); fatal_posix_service_status( status, -1, "sem_unlink error return status"); fatal_posix_service_status( errno, EINVAL, "sem_unlink errno value"); /* * XXX - Cant' create location OBJECTS_ERROR or OBJECTS_REMOTE. * sem_close and sem_unlink. */ puts( "Init: sem_unlink - UNSUCCESSFUL (ENOENT)" ); status = sem_unlink("sem2"); fatal_posix_service_status( status, -1, "sem_unlink error return status"); fatal_posix_service_status( errno, ENOENT, "sem_unlink errno ENOENT"); rtems_test_assert( (status == -1) && (errno == ENOENT) ); /* Try adding in unlinking before closing... (can we still open?) */ TEST_END(); rtems_test_exit(0); return NULL; /* just so the compiler thinks we returned something */ }
/** Cleanup existing shared memory segments. * @param name shared memory segment name */ void SharedMemoryRegistry::cleanup(const char *name) { shm_unlink(name ? name : DEFAULT_SHM_NAME); sem_unlink(name ? name : DEFAULT_SHM_NAME); }
//------------------------------------------------------------------------------ void timesynckcal_exit(void) { sem_close(syncSem_l); sem_unlink(TIMESYNC_SYNC_BSDSEM); }
/** Constructor. * @param name name of the shared memory region. Must follow the rules * set by shm_open(). If NULL defaults to "/fawkes-shmem-registry". */ SharedMemoryRegistry::SharedMemoryRegistry(const char *name) { __shm_name = name ? strdup(name) : strdup(DEFAULT_SHM_NAME); __sem = sem_open(__shm_name, O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP, 1); if (__sem == SEM_FAILED) { free(__shm_name); throw Exception(errno, "Failed to init shared memory registry semaphore"); } sem_wait(__sem); __shmfd = shm_open(__shm_name, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); bool created = false; if ((__shmfd < 0) && (errno == EEXIST)) { __shmfd = shm_open(__shm_name, O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); } else { if (ftruncate(__shmfd, sizeof(MemInfo)) != 0) { close(__shmfd); shm_unlink(__shm_name); sem_post(__sem); sem_close(__sem); sem_unlink(__shm_name); free(__shm_name); throw Exception(errno, "Failed to resize memory for shared memory registry"); } created = true; } if (__shmfd < 0) { sem_post(__sem); sem_close(__sem); sem_unlink(__shm_name); free(__shm_name); throw Exception(errno, "Failed to open shared memory registry"); } __meminfo = (MemInfo *)mmap(NULL, sizeof(MemInfo), PROT_READ | PROT_WRITE, MAP_SHARED, __shmfd, 0); if (__meminfo == MAP_FAILED) { close(__shmfd); sem_close(__sem); free(__shm_name); throw Exception(errno, "Failed to mmap shared memory registry"); } if (created) { memset(__meminfo, 0, sizeof(MemInfo)); for (unsigned int i = 0; i < MAXNUM_SHM_SEGMS; ++i) { __meminfo->segments[i].shmid = -1; } } __master = created; sem_post(__sem); }
int main(int argc, char* argv[]) { // Process config (to be filled completely // later). config_t config; config.idevice = 0; config.nx = nx; config.ny = ny; config.step = 0; // Create shared memory region. int fd = shm_open("/shmem_mmap_cuda_shm", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); if (fd == -1) { fprintf(stderr, "Cannot open shared region, errno = %d\n", errno); return errno; } // Create first semaphore (set to 0 to create it initially locked). sem_t* sem1 = sem_open("/shmem_mmap_cuda_sem1", O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 0); if (sem1 == SEM_FAILED) { fprintf(stderr, "Cannot open semaphore #1, errno = %d\n", errno); return errno; } // Create second semaphore (set to 0 to create it initially locked). sem_t* sem2 = sem_open("/shmem_mmap_cuda_sem2", O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 0); if (sem2 == SEM_FAILED) { fprintf(stderr, "Cannot open semaphore #2, errno = %d\n", errno); return errno; } // Call fork to create another process. // Standard: "Memory mappings created in the parent // shall be retained in the child process." pid_t fork_status = fork(); // From this point two processes are running the same code, if no errors. if (fork_status == -1) { fprintf(stderr, "Cannot fork process, errno = %d\n", errno); return errno; } // Get the process ID. int pid = (int)getpid(); // By fork return value we can determine the process role: // master or child (worker). int master = fork_status ? 1 : 0, worker = !master; int ndevices = 0; cudaError_t cuda_status = cudaGetDeviceCount(&ndevices); if (cuda_status != cudaSuccess) { fprintf(stderr, "Cannot get the cuda device count by process %d, status = %d\n", pid, cuda_status); return cuda_status; } // Return if no cuda devices present. if (master) printf("%d CUDA device(s) found\n", ndevices); if (!ndevices) return 0; ndevices = 1; size_t np = nx * ny; size_t size = np * sizeof(float); float* inout; if (!master) { // Lock semaphore to finish shared region configuration on master. int sem_status = sem_wait(sem1); if (sem_status == -1) { fprintf(stderr, "Cannot wait on semaphore by process %d, errno = %d\n", pid, errno); return errno; } // Map the shared region into the address space of the current process. inout = (float*)mmap(0, size * (ndevices + 1), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (inout == MAP_FAILED) { fprintf(stderr, "Cannot map shared region to memory by process %d, errno = %d\n", pid, errno); return errno; } } else { config.idevice = ndevices; // Set shared region size. int ftrunk_status = ftruncate(fd, size * (ndevices + 1)); if (ftrunk_status == -1) { fprintf(stderr, "Cannot truncate shared region, errno = %d\n", errno); return errno; } // Map the shared region into the address space of the current process. inout = (float*)mmap(0, size * (ndevices + 1), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (inout == MAP_FAILED) { fprintf(stderr, "Cannot map shared region to memory by process %d, errno = %d\n", pid, errno); return errno; } // Create input data. Let each device to have an equal piece // of single shared data array. float invdrandmax = 1.0 / RAND_MAX; for (size_t i = 0; i < np; i++) inout[i] = rand() * invdrandmax; for (int i = 0; i < ndevices; i++) memcpy(inout + np * (i + 1), inout, np * sizeof(float)); // Sync changed content with shared region. int msync_status = msync(inout, size * (ndevices + 1), MS_SYNC); if (msync_status == -1) { fprintf(stderr, "Cannot sync shared memory %p, errno = %d\n", inout, errno); return errno; } // Unlock semaphore to let other processes to move forward. int sem_status = sem_post(sem1); if (sem_status == -1) { fprintf(stderr, "Cannot post on semaphore by process %d, errno = %d\n", pid, errno); return errno; } } config.inout_cpu = inout + config.idevice * np; // Let workers to use CUDA devices, and master - the CPU. // Create device buffers. if (worker) { // Create device arrays for input and output data. cuda_status = cudaMalloc((void**)&config.in_dev, size); if (cuda_status != cudaSuccess) { fprintf(stderr, "Cannot allocate CUDA input buffer by process %d, status = %d\n", pid, cuda_status); return cuda_status; } cuda_status = cudaMalloc((void**)&config.out_dev, size); if (cuda_status != cudaSuccess) { fprintf(stderr, "Cannot allocate CUDA output buffer by process %d, status = %d\n", pid, cuda_status); return cuda_status; } } else { // Create device arrays for input and output data. config.in_dev = (float*)malloc(size); config.out_dev = (float*)malloc(size); } printf("Device %d initialized py process %d\n", config.idevice, pid); // Perform some "iterations" on data arrays, assigned to devices, // and shift input data array after each iteration. for (int i = 0; i < nticks; i++) { int status; if (master) { // Copy input data to device buffer. memcpy(config.in_dev, config.inout_cpu, size); status = pattern2d_cpu(1, config.nx, 1, 1, config.ny, 1, config.in_dev, config.out_dev, config.idevice); if (status) { fprintf(stderr, "Cannot execute pattern 2d by process %d, status = %d\n", pid, status); return status; } // Copy output data from device buffer. memcpy(config.inout_cpu, config.out_dev, size); // Sync with changed content in shared region. int msync_status = msync(inout, size * (ndevices + 1), MS_SYNC); if (msync_status == -1) { fprintf(stderr, "Cannot sync shared memory %p, errno = %d\n", inout, errno); return errno; } int sem_status = sem_post(sem1); if (sem_status == -1) { fprintf(stderr, "Cannot post on semaphore #1 by process %d, errno = %d\n", pid, errno); return errno; } sem_status = sem_wait(sem2); if (sem_status == -1) { fprintf(stderr, "Cannot post on semaphore #2 by process %d, errno = %d\n", pid, errno); return errno; } } else { // Copy input data to device buffer. cuda_status = cudaMemcpy(config.in_dev, config.inout_cpu, size, cudaMemcpyHostToDevice); if (cuda_status != cudaSuccess) { fprintf(stderr, "Cannot copy input data to CUDA buffer by process %d, status = %d\n", pid, cuda_status); return cuda_status; } status = pattern2d_gpu(1, config.nx, 1, 1, config.ny, 1, config.in_dev, config.out_dev, config.idevice); if (status) { fprintf(stderr, "Cannot execute pattern 2d by process %d, status = %d\n", pid, status); return status; } // Copy output data from device buffer. cuda_status = cudaMemcpy(config.inout_cpu, config.out_dev, size, cudaMemcpyDeviceToHost); if (cuda_status != cudaSuccess) { fprintf(stderr, "Cannot copy output data from CUDA buffer by process %d, status = %d\n", pid, cuda_status); return cuda_status; } // Sync with changed content in shared region. int msync_status = msync(inout, size * (ndevices + 1), MS_SYNC); if (msync_status == -1) { fprintf(stderr, "Cannot sync shared memory %p, errno = %d\n", inout, errno); return errno; } int sem_status = sem_wait(sem1); if (sem_status == -1) { fprintf(stderr, "Cannot wait on semaphore #1 by process %d, errno = %d\n", pid, errno); return errno; } sem_status = sem_post(sem2); if (sem_status == -1) { fprintf(stderr, "Cannot post on semaphore #2 by process %d, errno = %d\n", pid, errno); return errno; } } // At this point two processes are synchronized. config.step++; // Reassign porcesses' input data segments to show some // possible manipulation on shared memory. // Here we perform cyclic shift of data pointers. config.idevice++; config.idevice %= ndevices + 1; config.inout_cpu = inout + config.idevice * np; } // Release device buffers. if (worker) { cuda_status = cudaFree(config.in_dev); if (cuda_status != cudaSuccess) { fprintf(stderr, "Cannot release input buffer by process %d, status = %d\n", pid, cuda_status); return cuda_status; } cuda_status = cudaFree(config.out_dev); if (cuda_status != cudaSuccess) { fprintf(stderr, "Cannot release output buffer by process %d, status = %d\n", pid, cuda_status); return cuda_status; } } else { free(config.in_dev); free(config.out_dev); } printf("Device %d deinitialized py process %d\n", config.idevice, pid); // On master process perform results check: // compare each GPU result to CPU result. if (master) { float* control = inout + np * ndevices; for (int idevice = 0; idevice < ndevices; idevice++) { // Find the maximum abs difference. int maxi = 0, maxj = 0; float maxdiff = fabs(control[0] - (inout + idevice * np)[0]); for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { float diff = fabs( control[i + j * nx] - (inout + idevice * np)[i + j * nx]); if (diff > maxdiff) { maxdiff = diff; maxi = i; maxj = j; } } } printf("Device %d result abs max diff = %f @ (%d,%d)\n", idevice, maxdiff, maxi, maxj); } } // Unlink semaphore. if (master) { int sem_status = sem_unlink("/shmem_mmap_cuda_sem1"); if (sem_status == -1) { fprintf(stderr, "Cannot unlink semaphore #1 by process %d, errno = %d\n", pid, errno); return errno; } } // Close semaphore. int sem_status = sem_close(sem1); if (sem_status == -1) { fprintf(stderr, "Cannot close semaphore #1 by process %d, errno = %d\n", pid, errno); return errno; } // Unlink semaphore. if (master) { int sem_status = sem_unlink("/shmem_mmap_cuda_sem2"); if (sem_status == -1) { fprintf(stderr, "Cannot unlink semaphore #2 by process %d, errno = %d\n", pid, errno); return errno; } } // Close semaphore. sem_status = sem_close(sem2); if (sem_status == -1) { fprintf(stderr, "Cannot close semaphore #2 by process %d, errno = %d\n", pid, errno); return errno; } // Unmap shared region. close(fd); int munmap_status = munmap(inout, size * (ndevices + 1)); if (munmap_status == -1) { fprintf(stderr, "Cannot unmap shared region by process %d, errno = %d\n", pid, errno); return errno; } // Unlink shared region. if (master) { int unlink_status = shm_unlink("/shmem_mmap_cuda_shm"); if (unlink_status == -1) { fprintf(stderr, "Cannot unlink shared region by process %d, errno = %d\n", pid, errno); return errno; } } return 0; }
main (void) { pid_t pid_gui; pid_t pid_sim; pid_t pid_pport; int simChid; int kill_gui; int kill_sim; int kill_pport; int s_return; //---thread paramters--------------// pthread_attr_t attr; pthread_t timerThreadID; pthread_t keyboardThreadID; pthread_t blockIDThreadID; do { printf("\n=========================================================\n"); printf("Please Selet the Operating Mode:\n"); printf("1: Basic Orientation Mode for Block: 0-10).\n"); printf("2: Rotated Orientation Mode for Block:0-6). (alaph version)\n"); printf("===========================================================\n"); flushall(); scanf ("%c",&programMode); printf("You have selected: Mode %c.\n\n",programMode); flushall(); if((programMode != '1' )&&(programMode !='2')) { printf("Invalid Selection, Please Enter!\n"); flushall(); } } while(programMode != '1'&&programMode !='2'); // ----------------Share Memory---------------------------------------- shMem=shm_open("shared_memory", OFLAGS, 0777); if (shMem == -1) { printf("shared_memory failed to open...\n"); flushall(); } else { if (ftruncate (shMem,SIZE) == -1) { printf ("Failed to set size for -- shmem -- \n"); flushall(); } else { //mapping a shared memory location memLocation = mmap (0, SIZE, PROT, MFLAGS, shMem, 0); if (memLocation == MAP_FAILED) { printf (" Failed to map to shared memory...\n"); flushall(); } } } // ---------------Semorphore------------------------------------- // semorphore for shared memory sem = sem_open ("shared_sem", O_CREAT, S_IRWXG | S_IRWXO | S_IRWXU, 0); if (sem == (sem_t *)(-1)) { printf ("User: Memory Semaphore failed to open....\n"); flushall(); } else { sem_post(sem); } // -----------------------channel creation--------------------------- // Create a channels for the simulator and Gui // The ChannelCreate function returns the channel ID ChannelCreate(0); ChannelCreate(0); //ChannelCreate(0);//for pport simChid = 1; sleep(1); // Spawing a process for the GUI and Simulator pid_gui = spawnl(P_NOWAIT, "/usr/local/bin/gui_g", "gui_g", NULL); pid_sim = spawnl(P_NOWAIT, "/usr/local/bin/newGUIPport_g", "sim", NULL); pid_pport = spawnl(P_NOWAIT, "/usr/local/bin/testPport_g", "pport",NULL); sleep(1); //The Gui process automatically connect to the channel //Thus we only need to attach the simulator process to the created channel coidsim = ConnectAttach(0,pid_sim,simChid,0,0); // Display error message if connection failed if (coidsim == -1) { printf("coidsim error\n"); flushall(); exit(EXIT_FAILURE); } coidpport = ConnectAttach(0,pid_pport,simChid,0,0); // Display error message if connection failed if (coidpport == -1) { printf("coidpport error\n"); flushall(); exit(EXIT_FAILURE); } // --------------------------timer code---------------------------------- // Create a channel for sending a pulse to myself when timer expires timerChid = ChannelCreate(_NTO_CHF_UNBLOCK); if(timerChid == -1) { printf("timer Channel create failed\n"); flushall(); } timerCoid = ConnectAttach ( 0, getpid ( ), timerChid, 0, 0); if(timerCoid == -1 ) { printf ("Channel attach failed!\n"); flushall(); perror ( NULL ); exit ( EXIT_FAILURE); } // Set up pulse event for delivery when the first timer expires; pulse code = 8, pulse value = 0; SIGEV_PULSE_INIT (&timerEvent, timerCoid, SIGEV_PULSE_PRIO_INHERIT, 8, 0); // Create Timer if (timer_create (CLOCK_REALTIME, &timerEvent, &timerid) == -1) { printf ( "Failed to create a timer for pulse delivery\n"); flushall(); perror (NULL); exit ( EXIT_FAILURE); } // Setup one time timer for 2 second timer.it_value.tv_sec = 2; timer.it_value.tv_nsec = 0; timer.it_interval.tv_sec = 0; timer.it_interval.tv_nsec = 0; // --------------------------timer2 code---------------------------------- // Create a channel for sending a pulse to myself when timer expires timerChid2 = ChannelCreate(_NTO_CHF_UNBLOCK); if(timerChid2 == -1) { printf("timer Channel create failed\n"); flushall(); } timerCoid2 = ConnectAttach ( 0, getpid ( ), timerChid2, 0, 0); if(timerCoid2 == -1 ) { printf ("Channel attach failed!\n"); flushall(); perror ( NULL ); exit ( EXIT_FAILURE); } // Set up pulse event for delivery when the first timer expires; pulse code = 8, pulse value = 0; SIGEV_PULSE_INIT (&timerEvent2, timerCoid2, SIGEV_PULSE_PRIO_INHERIT, 8, 0); // Create Timer if (timer_create (CLOCK_REALTIME, &timerEvent2, &timerid2) == -1) { printf ( "Failed to create a timer for pulse delivery\n"); flushall(); perror (NULL); exit ( EXIT_FAILURE); } //-------------------timer monitor thread-------------------- pthread_attr_init(&attr); pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); pthread_create(&timerThreadID,&attr,timer_thread,NULL); if(timerThreadID == -1) { printf("Fail to create timer thread!"); flushall(); } else { printf("The timer thread ID is %i \n",timerThreadID); flushall(); } pthread_create(&timerThreadID,&attr,timer2_thread,NULL); if(timerThreadID == -1) { printf("Fail to create timer thread2!"); flushall(); } else { printf("The timer thread2 ID is %i \n",timerThreadID); flushall(); } // //----start the block Identification thread----------------- // pFile = fopen("Blocks.txt","w+"); pthread_create(&blockIDThreadID,&attr,blockID,NULL); if(blockIDThreadID == -1) { printf("Fail to create block indeptification thread!"); flushall(); } else { printf("The BlockID's thread ID is %i \n",blockIDThreadID); flushall(); } delay(10); //---------------------keyboard thread------------------------ pthread_create(&keyboardThreadID,&attr,keyboard_input,NULL); if(keyboardThreadID == -1) { printf("Fail to create keyboard input!"); flushall(); } else { printf("The keyboard_input ID is %i \n",timerThreadID); flushall(); } delay(10); //----------------GUI Monitor Thread--------------------- pthread_create(NULL,&attr,GUI_thread,NULL); delay(10); // --------------------SIM pulse Handler Loop Thread---------- pthread_create(NULL,&attr,Handlerloop_thread,NULL); delay(10); // --------------------SIM Monitor Thread--------------------- pthread_create(NULL,&attr,SIM_thread,NULL); delay(10); // --------------------Auto mode thread----------------------- pthread_create(NULL,&attr,auto_thread,NULL); delay(10); // --------------------others--------------------------------- // call mainLoop() mainLoop(); // sleep for 10sec printf("Sleep the program for 10 seconds\n"); flushall; sleep(10); // start release system resourse printf("Clean up and release system resourse\n"); flushall; // Kill the existing processes kill_gui = kill(pid_gui, 0); kill_sim = kill(pid_sim, 0); kill_pport = kill(pid_pport, 0); if (kill_gui == -1) { printf("GUI Kill failed\n"); flushall(); } if (kill_sim == -1) { printf("SIM Kill failed\n"); flushall(); } if (kill_pport == -1) { printf("PPort Kill failed\n"); flushall(); } // Close and unlink Semorphore sem_close(sem); s_return = sem_unlink("/dev/sem/home/quad6/workspace/Project_S1/shared_sem"); // Display error messae if semorphonre unlink is failed if (s_return == -1) { printf("a: %s\n", strerror( errno )); flushall(); } // Close, unmap, and unlink shared memory shm_close(shMem); munmap(shmLocation,SIZE); shm_unlink("shared_memory"); // Detach the connections and destroy the channels ConnectDetach(coidGui); ConnectDetach(coidsim); ConnectDetach(coidpport); ChannelDestroy(guiChid); ChannelDestroy(simChid); // fclose(pFile); }
int ipcon_create(IPConnection *ipcon, const char *host, const int port) { int i; for(i = 0; i < MAX_NUM_DEVICES; i++) { ipcon->devices[i] = NULL; } ipcon->pending_add_device = NULL; ipcon->enumerate_callback = NULL; ipcon->thread_receive_flag = true; ipcon->thread_callback_flag = true; ipcon->callback_queue_head = NULL; ipcon->callback_queue_tail = NULL; #ifdef _WIN32 WSADATA wsaData; // Initialize Winsock if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { return E_NO_STREAM_SOCKET; } ipcon->s = socket(AF_INET, SOCK_STREAM, 0); if(ipcon->s == INVALID_SOCKET) { return E_NO_STREAM_SOCKET; } #else ipcon->fd = socket(AF_INET, SOCK_STREAM, 0); if(ipcon->fd < 0) { return E_NO_STREAM_SOCKET; } #endif struct hostent *he = gethostbyname(host); if(he == NULL) { return E_HOSTNAME_INVALID; } memset(&ipcon->server, 0, sizeof(struct sockaddr_in)); memcpy(&ipcon->server.sin_addr, he->h_addr_list[0], he->h_length); ipcon->server.sin_family = AF_INET; ipcon->server.sin_port = htons(port); #ifdef _WIN32 if(connect(ipcon->s, (struct sockaddr *)&ipcon->server, sizeof(ipcon->server)) == SOCKET_ERROR) { return E_NO_CONNECT; } #else if(connect(ipcon->fd, (struct sockaddr *)&ipcon->server, sizeof(ipcon->server)) < 0) { return E_NO_CONNECT; } #endif #ifdef _WIN32 InitializeCriticalSection(&ipcon->add_device_mutex); #else pthread_mutex_init(&ipcon->add_device_mutex, NULL); #endif #ifdef _WIN32 InitializeCriticalSection(&ipcon->callback_queue_mutex); ipcon->callback_queue_semaphore = CreateSemaphore(NULL, 0, INT32_MAX, NULL); #elif defined __APPLE__ pthread_mutex_init(&ipcon->callback_queue_mutex, NULL); // Mac OS does not support unnamed semaphores, so we fake them. // Unlink first to ensure that there is no existing semaphore with that name. // Then open the semaphore to create a new one. Finally unlink it again to // avoid leaking the name. The semaphore will just work fine without a name. #define SEMAPHORE_NAME "tinkerforge-ipcon-internal" sem_unlink(SEMAPHORE_NAME); ipcon->callback_queue_semaphore = sem_open(SEMAPHORE_NAME, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IXUSR, 0); sem_unlink(SEMAPHORE_NAME); #else pthread_mutex_init(&ipcon->callback_queue_mutex, NULL); ipcon->callback_queue_semaphore = &ipcon->callback_queue_semaphore_object; sem_init(ipcon->callback_queue_semaphore, 0, 0); #endif #ifdef _WIN32 ipcon->thread_receive = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ipcon_receive_loop, (void*)ipcon, 0, (LPDWORD)&ipcon->thread_id_receive); if(ipcon->thread_receive == NULL) { return E_NO_THREAD; } ipcon->thread_callback = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ipcon_callback_loop, (void*)ipcon, 0, (LPDWORD)&ipcon->thread_id_callback); if(ipcon->thread_callback == NULL) { return E_NO_THREAD; } #else if(pthread_create(&ipcon->thread_receive, NULL, ipcon_receive_loop, (void*)ipcon) < 0) { return E_NO_THREAD; } if(pthread_create(&ipcon->thread_callback, NULL, ipcon_callback_loop, (void*)ipcon) < 0) { return E_NO_THREAD; } #endif return E_OK; }
ipc_t ipc_create(const char* name, int owner) { int isInited = 0; struct Queue* queue; ipc_t conn = malloc(sizeof(struct ipc_t)); sprintf(conn->name, "/arqvenger_%s", name); if ((conn->lock = sem_open(conn->name, O_CREAT | O_EXCL, 0666, 0)) == SEM_FAILED) { conn->lock = sem_open(conn->name, 0); if (conn->lock == SEM_FAILED) { print_errno("Failed adquiring named lock"); return NULL; } sem_wait(conn->lock); isInited = 1; } conn->fd = shm_open(conn->name, O_CREAT | O_RDWR, 0666); if (conn->fd == -1) { print_errno("shm_open failed"); sem_close(conn->lock); if (owner) { sem_unlink(conn->name); } free(conn); return NULL; } if (!isInited) { if (ftruncate(conn->fd, SHMEM_SIZE) == -1) { print_errno("Truncate failed"); sem_close(conn->lock); if (owner) { sem_unlink(conn->name); shm_unlink(conn->name); } free(conn); return NULL; } } conn->queue = mmap(NULL, SHMEM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, conn->fd, 0); if (conn->queue == (void*) -1) { print_errno("mmap"); sem_close(conn->lock); if (owner) { sem_unlink(conn->name); shm_unlink(conn->name); } free(conn); return NULL; } if (isInited) { sem_post(conn->lock); return conn; } queue = conn->queue; for (size_t i = 0; i < ENTRIES_PER_QUEUE; i++) { queue->index[i] = -1; queue->slots[i].len = 0; } queue->readWait = ipc_sem_create(0); queue->writeSem = ipc_sem_create(ENTRIES_PER_QUEUE); if (queue->readWait == -1 || queue->writeSem == -1) { print_errno("failed creating sems"); sem_close(conn->lock); ipc_sem_destroy(queue->readWait); ipc_sem_destroy(queue->writeSem); munmap(conn->queue, SHMEM_SIZE); if (owner) { sem_unlink(conn->name); shm_unlink(conn->name); } free(conn); return NULL; } sem_post(conn->lock); return conn; }
int main (int arc, char ** argv, char **envp) { char temp[16]; int fd; //system("rm test.txt"); if ( (fd = open("./test.txt", O_RDWR|O_CREAT)) == -1) { printf("open file error\n"); return 1; } write(fd, "0\0", 2); close(fd); sem_t * sr; if ( (sr = sem_open ("/_semName_", O_RDWR|O_CREAT, 0666, 1)) == SEM_FAILED) { printf("sem_open error\n"); return 1; } int currentValue; sem_getvalue(sr,¤tValue); printf("current value of sem is %d\n", currentValue); int pid; if ( (pid = fork()) == -1) { printf("fork error\n"); return 1; } else if (pid == 0)//child { char temp[16]; int fd,i; for (i=0; i<n; ++i) { //int value; //sem_getvalue(sr, &value); //printf("child before: sem value is %d\n",value); sem_wait(sr); //sem_getvalue(sr, &value); //printf("child after: sem value is %d\n",value); if ( (fd = open("./test.txt", O_RDWR|O_CREAT)) == -1) { printf("open error\n"); return 1; } read(fd, &temp, 16); int number = atoi(temp); number++; lseek(fd, 0, SEEK_SET); sprintf(temp, "%d", number); printf("child`s value is %s\n", temp); write(fd, &temp, strlen(temp)); write(fd, "\0", 1); close(fd); sem_post(sr); } } else//parent { char temp[16]; int fd,i; for (i=0; i<n; ++i) { //int value; //sem_getvalue(sr, &value); //printf("parent before: sem value is %d\n",value); sem_wait(sr); //sem_getvalue(sr, &value); //printf("parent after: sem value is %d\n",value); if ( (fd = open("./test.txt", O_RDWR|O_CREAT)) == -1) { printf("open error\n"); return 1; } read(fd, &temp, 16); int number = atoi(temp); number++; lseek(fd, 0, SEEK_SET); sprintf(temp, "%d", number); printf("parent`s temp is %s\n", temp); write(fd, &temp, strlen(temp)); write(fd, "\0", 1); close(fd); sem_post(sr); } sem_unlink("/_semName_"); } return 0; }
int mutex_sem_close(sem_t *mutex) { sem_close(mutex); sem_unlink(MUTEX_SEM_NAME); }
int main(int argc, char **argv) { int i, nprocs; pid_t childpid[MAXNPROC]; double st; // stop time if (argc != 3) { fprintf(stderr, "usage: incr_pxsem7 <#loops> <#processes>\n"); exit(1); } nloop = atoi(argv[1]); nprocs = min(atoi(argv[2]), MAXNPROC); /* 4get shared memory for parent and children */ if ((shared = my_shm(sizeof(struct shared))) == MAP_FAILED) { perror("my_shm error"); exit(1); } /* 4initialize named semaphore to 0 */ sem_unlink(NAME); /* error OK */ if ((pmutex = sem_open(NAME, O_CREAT | O_EXCL, FILE_MODE, 0)) == SEM_FAILED) { fprintf(stderr, "sem_open error for %s: %s\n", NAME, strerror(errno)); exit(1); } /* 4create all the children */ for (i = 0; i < nprocs; i++) { if ( (childpid[i] = fork()) == -1) { perror("fork error"); exit(1); } else if (childpid[i] == 0) { if (sem_close(pmutex) == -1) { /* the one kept open by fork() */ perror("sem_close error"); exit(1); } if ((cmutex = sem_open(NAME, 0)) == SEM_FAILED) { fprintf(stderr, "sem_open error for %s: %s\n", NAME, strerror(errno)); exit(1); } incr(NULL); exit(0); } } /* 4parent: start the timer and release the semaphore */ if (start_time() == -1) { perror("start_time error"); exit(1); } if (sem_post(pmutex) == -1) { perror("sem_post error"); exit(1); } /* 4wait for all the children */ for (i = 0; i < nprocs; i++) { if (waitpid(childpid[i], NULL, 0) == -1) { perror("waitpid error"); exit(1); } } if ((st = stop_time()) == 0.0) { perror("stop_time error"); exit(1); } printf("microseconds: %.0f usec\n", st); if (shared->counter != nloop * nprocs) printf("error: counter = %ld\n", shared->counter); if (sem_unlink(NAME) == -1) { perror("sem_unlink error"); exit(1); } exit(0); }
int highlander_clean(void) { // remove the named semaphores sem_unlink("/power_wrapperK"); sem_unlink("/power_wrapperL"); }
static void remove_sem (int status, void *arg) { sem_unlink (arg); }
int main (int argc, char **argv) { pid_t child_pid; int curr_opt = 1; bool use_mt = false, use_direct = false; long offset; while(curr_opt < argc) { if (0 == strcmp(argv[curr_opt], "-m")) { use_mt = true; curr_opt++; continue; } else if (0 == strcmp(argv[curr_opt], "-f")) { use_direct = true; curr_opt++; continue; } else if (0 == strcmp(argv[curr_opt], "--exclude-monotonic")) { setenv("FAKETIME_DONT_FAKE_MONOTONIC", "1", true); curr_opt++; continue; } else if ((0 == strcmp(argv[curr_opt], "-v")) || (0 == strcmp(argv[curr_opt], "--version"))) { printf("\n%s: Version %s\n" "For usage information please use '%s --help'.\n", argv[0], version, argv[0]); exit(EXIT_SUCCESS); } else if ((0 == strcmp(argv[curr_opt], "-h")) || (0 == strcmp(argv[curr_opt], "-?")) || (0 == strcmp(argv[curr_opt], "--help"))) { usage(argv[0]); exit(EXIT_SUCCESS); } else { /* we parsed all options */ break; } } /* we need at least a timestamp string and a command to run */ if (argc - curr_opt < 2) { usage(argv[0]); exit(EXIT_FAILURE); } if (!use_direct) { // TODO get seconds int pfds[2]; (void) (pipe(pfds) + 1); int ret = EXIT_SUCCESS; if (0 == (child_pid = fork())) { close(1); /* close normal stdout */ (void) (dup(pfds[1]) + 1); /* make stdout same as pfds[1] */ close(pfds[0]); /* we don't need this */ if (EXIT_SUCCESS != execlp(date_cmd, date_cmd, "-d", argv[curr_opt], "+%s",(char *) NULL)) { perror("Running (g)date failed"); exit(EXIT_FAILURE); } } else { char buf[256] = {0}; /* e will have way less than 256 digits */ close(pfds[1]); /* we won't write to this */ (void) (read(pfds[0], buf, 256) + 1); waitpid(child_pid, &ret, 0); if (ret != EXIT_SUCCESS) { printf("Error: Timestamp to fake not recognized, please re-try with a " "different timestamp.\n"); exit(EXIT_FAILURE); } offset = atol(buf) - time(NULL); ret = snprintf(buf, sizeof(buf), "%s%ld", (offset >= 0)?"+":"", offset); setenv("FAKETIME", buf, true); close(pfds[0]); /* finished reading */ } } else { /* simply pass format string along */ setenv("FAKETIME", argv[curr_opt], true); } int keepalive_fds[2]; (void) (pipe(keepalive_fds) + 1); /* we just consumed the timestamp option */ curr_opt++; { /* create semaphores and shared memory */ int shm_fd; sem_t *sem; struct ft_shared_s *ft_shared; char shared_objs[PATH_BUFSIZE * 2 + 1]; /* * Casting of getpid() return value to long needed to make GCC on SmartOS * happy, since getpid's return value's type on SmartOS is long. Since * getpid's return value's type is int on most other systems, and that * sizeof(long) always >= sizeof(int), this works on all platforms without * the need for crazy #ifdefs. */ snprintf(sem_name, PATH_BUFSIZE -1 ,"/faketime_sem_%ld", (long)getpid()); snprintf(shm_name, PATH_BUFSIZE -1 ,"/faketime_shm_%ld", (long)getpid()); if (SEM_FAILED == (sem = sem_open(sem_name, O_CREAT|O_EXCL, S_IWUSR|S_IRUSR, 1))) { perror("sem_open"); exit(EXIT_FAILURE); } /* create shm */ if (-1 == (shm_fd = shm_open(shm_name, O_CREAT|O_EXCL|O_RDWR, S_IWUSR|S_IRUSR))) { perror("shm_open"); if (-1 == sem_unlink(argv[2])) { perror("sem_unlink"); } exit(EXIT_FAILURE); } /* set shm size */ if (-1 == ftruncate(shm_fd, sizeof(uint64_t))) { perror("ftruncate"); cleanup_shobjs(); exit(EXIT_FAILURE); } /* map shm */ if (MAP_FAILED == (ft_shared = mmap(NULL, sizeof(struct ft_shared_s), PROT_READ|PROT_WRITE, MAP_SHARED, shm_fd, 0))) { perror("mmap"); cleanup_shobjs(); exit(EXIT_FAILURE); } if (sem_wait(sem) == -1) { perror("sem_wait"); cleanup_shobjs(); exit(EXIT_FAILURE); } /* init elapsed time ticks to zero */ ft_shared->ticks = 0; ft_shared->file_idx = 0; ft_shared->start_time.real.tv_sec = 0; ft_shared->start_time.real.tv_nsec = -1; ft_shared->start_time.mon.tv_sec = 0; ft_shared->start_time.mon.tv_nsec = -1; ft_shared->start_time.mon_raw.tv_sec = 0; ft_shared->start_time.mon_raw.tv_nsec = -1; if (-1 == munmap(ft_shared, (sizeof(struct ft_shared_s)))) { perror("munmap"); cleanup_shobjs(); exit(EXIT_FAILURE); } if (sem_post(sem) == -1) { perror("semop"); cleanup_shobjs(); exit(EXIT_FAILURE); } snprintf(shared_objs, sizeof(shared_objs), "%s %s", sem_name, shm_name); setenv("FAKETIME_SHARED", shared_objs, true); sem_close(sem); } { char *ftpl_path; #ifdef __APPLE__ ftpl_path = PREFIX "/libfaketime.1.dylib"; FILE *check; check = fopen(ftpl_path, "ro"); if (check == NULL) { ftpl_path = PREFIX "/lib/faketime/libfaketime.1.dylib"; } else { fclose(check); } setenv("DYLD_INSERT_LIBRARIES", ftpl_path, true); setenv("DYLD_FORCE_FLAT_NAMESPACE", "1", true); #else { char *ld_preload_new, *ld_preload = getenv("LD_PRELOAD"); size_t len; if (use_mt) { /* * on MultiArch platforms, such as Debian, we put a literal $LIB into LD_PRELOAD. */ #ifndef MULTI_ARCH ftpl_path = PREFIX LIBDIRNAME "/libfaketimeMT.so.1"; #else ftpl_path = PREFIX "/$LIB/faketime/libfaketimeMT.so.1"; #endif } else { #ifndef MULTI_ARCH ftpl_path = PREFIX LIBDIRNAME "/libfaketime.so.1"; #else ftpl_path = PREFIX "/$LIB/faketime/libfaketime.so.1"; #endif } len = ((ld_preload)?strlen(ld_preload) + 1: 0) + 1 + strlen(ftpl_path); ld_preload_new = malloc(len); snprintf(ld_preload_new, len ,"%s%s%s", (ld_preload)?ld_preload:"", (ld_preload)?":":"", ftpl_path); setenv("LD_PRELOAD", ld_preload_new, true); free(ld_preload_new); } #endif } /* run command and clean up shared objects */ if (0 == (child_pid = fork())) { close(keepalive_fds[0]); /* only parent needs to read this */ if (EXIT_SUCCESS != execvp(argv[curr_opt], &argv[curr_opt])) { perror("Running specified command failed"); exit(EXIT_FAILURE); } } else { int ret; char buf; close(keepalive_fds[1]); /* only children need keep this open */ waitpid(child_pid, &ret, 0); (void) (read(keepalive_fds[0], &buf, 1) + 1); /* reads 0B when all children exit */ cleanup_shobjs(); if (WIFSIGNALED(ret)) { fprintf(stderr, "Caught %s\n", strsignal(WTERMSIG(ret))); exit(EXIT_FAILURE); } exit(WEXITSTATUS(ret)); } return EXIT_SUCCESS; }
/* The main test function. */ int main(void) { int ret, value; sem_t *sem; /* Initialize output */ output_init(); /* Create the semaphore */ sem = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0777, 2); if (sem == SEM_FAILED && errno == EEXIST) { sem_unlink(SEM_NAME); sem = sem_open(SEM_NAME, O_CREAT | O_EXCL, 0777, 2); } if (sem == SEM_FAILED) { UNRESOLVED(errno, "Failed to create the semaphore"); } /* Use the semaphore to change its value. */ do { ret = sem_wait(sem); } while (ret != 0 && errno == EINTR); if (ret != 0) { UNRESOLVED(errno, "Failed to wait for the semaphore"); } /* Here, count is 1. Now, close the semaphore */ ret = sem_close(sem); if (ret != 0) { UNRESOLVED(errno, "Failed to close the semaphore"); } /* Open the semaphore again */ sem = sem_open(SEM_NAME, O_CREAT, 0777, 3); if (sem == SEM_FAILED) { UNRESOLVED(errno, "Failed to re-open the semaphore"); } /* Check current semaphore count */ ret = sem_getvalue(sem, &value); if (ret != 0) { UNRESOLVED(errno, "Failed to get semaphore value"); } if (value != 1) { output("Got value: %d\n", value); FAILED("The semaphore count has changed after sem_close"); } /* Now, we can destroy all */ ret = sem_close(sem); if (ret != 0) { UNRESOLVED(errno, "Failed to close the semaphore"); } ret = sem_unlink(SEM_NAME); if (ret != 0) { UNRESOLVED(errno, "Failed to unlink the semaphore"); } /* Test passed */ #if VERBOSE > 0 output("Test passed\n"); #endif PASSED; }
int main(int argc, char** argv) { //INITIALIZATION //////////////// printf("\nMULE starting, please wait...\n"); if(signal(SIGUSR1, sig_mule) == SIG_ERR) { fprintf(stderr, "\nCRITICAL: mule signals can not be handled!\n"); exit(EXIT_FAILURE); } errno = 0; int config_fd = open("config", O_RDONLY); if(config_fd < 0) { perror("open"); return 1; } int16_t per_cnt = (int16_t)getPeripheralCNT(config_fd);//counts the potential peripherals if(per_cnt == 0xFF) return 1; if(!per_cnt) { printf("\nNo peripherals to load.\n"); } else { load_t* load = malloc(per_cnt * sizeof(load_t)); if(load == NULL) { perror("malloc"); return 1; } per_cnt = getLoad(config_fd, load); if(per_cnt < 0) return 1; else if(!per_cnt) printf("\nNo peripherals to load.\n"); load = realloc(load, per_cnt); if(per_cnt && load == NULL) { perror("realloc"); return 1; } //Alocate shared memory ////////////////////// int sim_pins = shm_open("/sim_pins", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if(sim_pins < 0) { perror("shm_open"); return 1; } int per_pins = shm_open("/per_pins", O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if(per_pins < 0) { printf("\n\n\tS_IWGRP failed without sudo\n\n"); perror("shm_open"); return 1; } if((ftruncate(sim_pins, 41 * sizeof(uint8_t))) < 0) { perror("ftruncate"); return 1; } if((ftruncate(per_pins, 41 * sizeof(uint8_t))) < 0) { perror("ftruncate"); return 1; } if(fcntl(sim_pins, F_SETFD, (fcntl(sim_pins, F_GETFD, 0) & (~FD_CLOEXEC))) < 0) { perror("fcntl"); return 1; } if(fcntl(per_pins, F_SETFD, (fcntl(per_pins, F_GETFD, 0) & (~FD_CLOEXEC))) < 0) { perror("fcntl"); return 1; } ///////////////////// //Allocate strings of the appropriate length, for passing the file descriptors ////////////////////////////////////////////////////////////////////////////// struct rlimit cur_lim; if(getrlimit(RLIMIT_NOFILE, &cur_lim) < 0) { perror("getrlimit"); return 1; } uint8_t digit_no = (uint8_t)log10(cur_lim.rlim_max) + 1; char* sim_pins_str = calloc(digit_no, sizeof(char)); if(sim_pins_str == NULL) { perror("calloc"); return 1; } char* per_pins_str = calloc(digit_no, sizeof(char)); if(per_pins_str == NULL) { perror("calloc"); return 1; } if(sprintf(sim_pins_str, "%d", sim_pins) < 0) { perror("sprintf"); return 1; } if(sprintf(per_pins_str, "%d", per_pins) <0) { perror("sprintf"); return 1; } ///////////////////////////////////////////////////////////////////////////// //Open necessary semaphores /////////////////////////// const char* sem_names[5] = {NULL, NULL, NULL, NULL, NULL}; const char P0_sem_nm[] = "/P0_sem"; const char P1_sem_nm[] = "/P1_sem"; const char P2_sem_nm[] = "/P2_sem"; const char P3_sem_nm[] = "/P3_sem"; const char othr_sem_nm[] = "/othr_sem"; sem_t* sems[5] = {NULL, NULL, NULL, NULL}; uint8_t i = 0; for(i = 0; i < per_cnt; ++i) { if(((load + i) -> ports)[0]) sem_names[0] = P0_sem_nm; if(((load + i) -> ports)[1]) sem_names[1] = P1_sem_nm; if(((load + i) -> ports)[2]) sem_names[2] = P2_sem_nm; if(((load + i) -> ports)[3]) sem_names[3] = P3_sem_nm; if(((load + i) -> ports)[4]) sem_names[4] = othr_sem_nm; } for(i = 0; i < 5; ++i) { if(sem_names[i] != NULL) { sems[i] = sem_open(sem_names[i], O_CREAT, S_IRUSR | S_IWUSR, 1); if(sems[i] == SEM_FAILED) { perror("sem_open"); return 1; } } } ////////////////////////// if(argc > 1 && !strcmp(argv[1], "--clean")) goto CRASH_CLN; //setup the exec arguments, fork(), execl() ////////////////////////////////////////// pid_t* peripherals = NULL; if((peripherals = calloc(per_cnt, sizeof(pid_t))) == NULL) { perror("calloc"); return 1; } uint8_t j, k; char progname[256]; for(i = 0; i < per_cnt; ++i) { //retrieve the name of the program to be executed, from the pathname ///////////////////////////////////////////////////////////////////// j = strlen((load + i) -> pathname); while(((load + i) -> pathname)[j] != '/') { progname[j] = ((load + i) -> pathname)[j]; if(j-- == 0) break; } //if the above loop exited by '/' encounter, progname will contain garbage at the beginning, which has to be removed //j points to the garbage place farthest to the right, should it exist, so it has to be advanced by one if(++j)//if there is no garbage, j overflowed to 255, so after being incremented, it will become zero once again for(k = 0; j <= strlen(progname); ++k) progname[k] = progname[j++]; //////////////////////////////////////////////////////////////////// char empty[] = "x"; char* argv[9] = {empty, empty, empty, empty, empty, empty, empty, empty, NULL}; argv[0] = progname; argv[1] = sim_pins_str; argv[2] = per_pins_str; if(((load + i) -> ports)[0]) argv[3] = sem_names[0]; if(((load + i) -> ports)[1]) argv[4] = sem_names[1]; if(((load + i) -> ports)[2]) argv[5] = sem_names[2]; if(((load + i) -> ports)[3]) argv[6] = sem_names[3]; if(((load + i) -> ports)[4]) argv[7] = sem_names[4]; if((peripherals[i] = fork()) < 0) { perror("fork"); return 1; } if(!peripherals[i]) { if(execv((load + i) -> pathname, argv) < 0) { printf("\nERROR: Failed to execute peripheral %d pathname: %s" "\nProceeding with next one.\n", i, ((load + i) -> pathname)); perror("execv"); exit(EXIT_FAILURE); } } } ///////////////////////////////////////// //exec the MULE /////////////// pid_t mule = fork(); if(mule < 0) { perror("fork"); return 1; } if(!mule) { if(execl("mule", "mule", sim_pins_str, per_pins_str, P0_sem_nm, P1_sem_nm, P2_sem_nm, P3_sem_nm, othr_sem_nm, NULL) < 0) { printf("\nCRITICAL: Failed to execute the simulator!\n"); perror("execl"); exit(EXIT_FAILURE); } } ////////////// close(fileno(stdin)); sleep(1); //CLEANUP ///////// sigset_t mask; sigfillset(&mask); sigdelset(&mask, SIGUSR1); sigdelset(&mask, SIGINT); sigprocmask(SIG_SETMASK, &mask, NULL); sigsuspend(&mask); kill(mule, SIGINT); int status; for(i = 0; i < per_cnt; ++i) { kill(peripherals[i], SIGINT); wait(&status); fprintf(stderr, "\nEXIT STATUS %d\n", status); } wait(&status);//wait for the MULE CRASH_CLN: close(sim_pins); close(per_pins); shm_unlink("/sim_pins"); shm_unlink("/per_pins"); for(i = 0; i < 5; ++i) { sem_close(sems[i]); sem_unlink(sem_names[i]); } sem_unlink("/ROM_sim_sem"); sem_unlink("/sim_ROM_sem"); printf("\nSimulation ended...\n"); ///////// }// //////////////// return 0; }