int main(int argc, char **argv) { // _MM_ROUND_NEAREST // _MM_ROUND_DOWN // _MM_ROUND_UP // _MM_ROUND_TOWARD_ZERO // _MM_SET_ROUNDING_MODE(_MM_ROUND_NEAREST); if (argc != 5) { printf("Invalid arguments\n"); printf("\tprogram height width ix iy\n"); exit(EXIT_FAILURE); } struct timeval t, t2; int height = atoi(argv[1]), width = atoi(argv[2]); float ix = atof(argv[3]), //zoom en x iy = atof(argv[4]); //zoom en y int delay = 2; short *mirror = NULL; //donde dira el padre que empieza el espejo global short *scale = NULL; //donde dira el padre que hay que guardar las cosas //Las dos siguientes las modifica MPI int nprocs, myid; MPI_Init(&argc, &argv);//inicializamos mpi MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); int aux_rows[nprocs];//Las filas con las que trabajara cada proceso int size_send_child[nprocs];//El numero de elementos a enviar a cada hijo int aux_split[nprocs];//Es para saber donde empezar a contar (este es para enviar a los hijos) int size_send_dad[nprocs]; //para saber el tamano que se le va a enviar al padre int aux_begin[nprocs]; //Es el para saber donde empezar a contar (este es para enviar al padre) //Con esto indicamos que todos saben lo que tienen todos fill_aux_rows(aux_rows, nprocs, height, delay); fill_size_send_child(size_send_child, nprocs, aux_rows, width, delay); fill_aux_split(aux_split, nprocs, size_send_child[0], width, delay); fill_size_send_dady(size_send_dad, nprocs, aux_rows, width, ix, iy, delay); fill_aux_begin(aux_begin, nprocs, size_send_dad[0]); if (myid == 0) {//Parent process short *originalImage = malloc(sizeof(short) * height * width); //Imagen original mirror = malloc(sizeof(short) * (height+delay*2) * (width+delay*2)); //Imagen en espejo if (originalImage == NULL || mirror == NULL) { exit_msg("main: cannot allocate memory", myid); } getImage(originalImage, height, width); getMirror(originalImage, mirror, height, width, delay); free(originalImage); gettimeofday(&t, NULL);//Empezamos a contar el tiempo } short *work = malloc(sizeof(short) * (aux_rows[myid]) * (width+2*delay) ); //con la que trabajara cada proceso if (work == NULL) exit_msg("main: cannot allocate memory (for work)", myid); //Enviamos a los procesos la informacion if (0 != MPI_Scatterv(mirror, size_send_child, aux_split, MPI_SHORT, work, size_send_child[myid], MPI_SHORT, 0, MPI_COMM_WORLD)) exit_msg("main: MPI_Scatterv", myid); short *result = malloc(sizeof(short) * ((int) ((aux_rows[myid]-2*delay)*iy)) * (int) (width*ix)); if (result == NULL) exit_msg("main: cannot allocate memory (for result)", myid); getScale(work, result, aux_rows[myid]-2*delay, width, delay, ix, iy); free(work); if (myid == 0) { free(mirror); scale = malloc(sizeof(short) * ((int) (height*iy)) * ((int) (width*ix))); // donde se guardara el resultado final } //Los procesos envian la informacion al padre if (0 != MPI_Gatherv(result, size_send_dad[myid], MPI_SHORT, scale, size_send_dad, aux_begin, MPI_SHORT, 0, MPI_COMM_WORLD)) exit_msg("main: MPI_Gatherv", myid); if (myid == 0) { gettimeofday(&t2, NULL); struct timeval diff; diff_time(&diff, &t2, &t); print_image(scale, height*iy, width*ix); printf("Tiempo = %ld:%ld(seg:mseg)\n\n", diff.tv_sec, diff.tv_usec/1000 ); } MPI_Finalize(); //Clean UP for MPI exit(EXIT_SUCCESS); }
void OsgNav::preFrame() { int i, j; vpr::Interval cur_time = mWand->getTimeStamp(); vpr::Interval diff_time(cur_time - mLastPreFrameTime); if (mLastPreFrameTime.getBaseVal() >= cur_time.getBaseVal()) { diff_time.secf(0.); } float time_delta = diff_time.secf(); mLastPreFrameTime = cur_time; // Get wand data gmtl::Matrix44f wandMatrix = mWand->getData(); gmtl::Matrix44f headMatrix = mHead->getData(); if(moduleRegistry!=NULL) { if(wandMatrix(1,1)!=0 && wandMatrix(3,3)!=0 && *(moduleRegistry->getAllowMovement())) { if (mButton0->getData() == gadget::Digital::TOGGLE_ON) { moduleRegistry->getInputManager()->jump(); } float alpha = wandMatrix(2,1)/wandMatrix(1,1); float beta = wandMatrix(1,0); if(alpha > 0.6) { alpha = 0.6; } if(beta > 0.7) { beta = 0.7; } if(alpha < -0.6) { alpha = -0.6; } if(beta < -0.7) { beta = -0.7; } if(alpha > 0.1) { moduleRegistry->getInputManager()->moveBehind(0.8*alpha*alpha); } if(alpha < -0.2) { moduleRegistry->getInputManager()->moveFront(2*alpha*alpha); } if(beta > 0.1) { *(moduleRegistry->getCameraAngle()) -= beta*beta*time_delta*3; } if(beta < -0.1) { *(moduleRegistry->getCameraAngle()) += beta*beta*time_delta*3; } // if (mButton1->getData() == gadget::Digital::ON) // { // *(moduleRegistry->getCameraAngle()) -= time_delta*2; // } // if (mButton2->getData() == gadget::Digital::ON) // { // *(moduleRegistry->getCameraAngle()) += time_delta*2; // } } std::stringstream out; for(i = 0; i<4; i++) { for(j = 0; j<4; j++) { out << wandMatrix(i,j) << " "; } out << std::endl; } *(moduleRegistry->getText2D()->print()) = out.str(); moduleRegistry->getScene()->run(time_delta); } // Update the navigation using the time delta between mNavigator.update(time_delta); }
int main(int argc, char *argv[]) { int ret; pid_t pid; int pipeFd[2]; uint8_t *buf_p; setlocale(LC_NUMERIC, ""); // process cmdline arguments if (!process_cmdline_args(argc, argv)) exit(EXIT_FAILURE); // verify parameters if (blockCnt_G == 0) { printf("please specify a block count\n\n"); usage(argv[0]); exit(EXIT_FAILURE); } if (blockSiz_G == 0) { printf("please specify a block size\n\n"); usage(argv[0]); exit(EXIT_FAILURE); } // create pipe ret = pipe(pipeFd); if (ret != 0) { perror("pipe2"); exit(EXIT_FAILURE); } // create buffer buf_p = (uint8_t*)malloc(blockSiz_G); if (buf_p == NULL) { perror("malloc()"); exit(EXIT_FAILURE); } // fork child pid = fork(); switch (pid) { // error case -1: perror("fork()"); exit(EXIT_FAILURE); // child writes to pipe (closes read) case 0: { size_t i; close(pipeFd[PIPE_RD]); for (i=0; i<blockCnt_G; ++i) write(pipeFd[PIPE_WR], buf_p, blockSiz_G); break; } // parent reads from pipe (closes write) default: { struct timespec timeBefore, timeAfter, timeDiff; double sec, bw; close(pipeFd[PIPE_WR]); clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &timeBefore); while (read(pipeFd[PIPE_RD], buf_p, blockSiz_G)); clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &timeAfter); close(pipeFd[PIPE_RD]); timeDiff = diff_time(timeBefore, timeAfter); sec = (double)timeDiff.tv_sec + ((double)timeDiff.tv_nsec * (double)1e-9); bw = ((double)blockCnt_G * (double)blockSiz_G) / sec; printf("elapsed time: %f sec\n", sec); printf(" bytes: %zd\n", blockCnt_G * blockSiz_G); printf(" bandwidth: %'.0f bytes/second\n", bw); break; } } free(buf_p); return 0; }
void velocityNav::update() { //stopWatch.stop(); //stopWatch.start(); vpr::Interval cur_time = mNavWand->getTimeStamp(); vpr::Interval diff_time(cur_time-mLastTimeStamp); mTimeDelta = diff_time.secf(); /* Cluster Sync Debug code std::cout << "Delta: " << diff_time.getBaseVal() << std::endl; std::cout << "Current: " << cur_time.getBaseVal() << "Last: " << mLastTimeStamp.getBaseVal() << "\n" << std::endl; */ mLastTimeStamp = cur_time; if ( mTimeDelta > 2.0f ) // If the time is greater than 2 seconds ( 1/2 fps) { vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL) << clrOutNORM(clrCYAN,"VelNav: timeInstant too large: ") << mTimeDelta << std::endl << vprDEBUG_FLUSH; //stopWatch.stop(); // Get a REALLY small delta time //stopWatch.start(); } //vprDEBUG_BEGIN(vprDBG_ALL,0) // << "VelNav: ----- Update ----\n" << vprDEBUG_FLUSH; //vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL) // << "VelNav: timeInstant: " << mTimeDelta << std::endl // << vprDEBUG_FLUSH; // If we are not supposed to be active, then don't run if ( ! this->isActive() ) { return; } ////////////////////////////////// // do navigations... ////////////////////////////////// // Define axes, in Juggler/OpenGL coordinate system (right handed) gmtl::Vec3f trackerZaxis(0.0f, 0.0f, 1.0f); gmtl::Vec3f trackerXaxis(1.0f, 0.0f, 0.0f); gmtl::Vec3f trackerYaxis(0.0f, 1.0f, 0.0f); // 9.8 m/s (METERS) const gmtl::Vec3f gravity_meters_per_second(0.0f, -9.8f, 0.0f); // to be set by switch (mUnits == METERS) gmtl::Vec3f gravity(0.0f, -9.8f, 0.0f); switch (mUnits) { case FEET: meters2feet(gravity_meters_per_second, gravity); break; default: case METERS: gravity = gravity_meters_per_second; break; } if ((mAllowRot) && (mRotating)) { // Interpolates the rotation, and updates mCurPos matrix this->scaled_rotate(mRotationalAcceleration); } if (mMode == DRIVE) { // get the axes of the tracking/pointing device // NOTE: constrain to the Y axis in GROUND mode (no flying/hopping or // diving faster than gravity allows) gmtl::Matrix44f constrainedToY; //mRotationalAcceleration.constrainRotAxis(false, true, false, // constrainedToY); gmtl::EulerAngleXYZf euler(0.0f, gmtl::makeYRot(mRotationalAcceleration), 0.0f); gmtl::setRot(constrainedToY, euler); // Only allow Yaw (rot y) gmtl::xform(trackerZaxis, constrainedToY, trackerZaxis); gmtl::xform(trackerXaxis, constrainedToY, trackerXaxis); gmtl::xform(trackerYaxis, constrainedToY, trackerYaxis); } else if (mMode == FLY) { // get the axes of the tracking/pointing device gmtl::xform(trackerZaxis, mRotationalAcceleration, trackerZaxis); gmtl::xform(trackerXaxis, mRotationalAcceleration, trackerXaxis); gmtl::xform(trackerYaxis, mRotationalAcceleration, trackerYaxis); } // this is used to accumulate velocity added by navigation gmtl::Vec3f velocityAccumulator(0.0f, 0.0f, 0.0f); if (mMode == DRIVE) // if DRIVING --> we have GRAVITY { // add the velocity this timeslice/frame by the acceleration from // gravity. velocityAccumulator += mVelocityFromGravityAccumulator; //vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL) // << "velNav: drive: gravAccum: " // << mVelocityFromGravityAccumulator << vprDEBUG_FLUSH; // recalculate the current downward velocity from gravity. // this vector then is accumulated with the rest of the velocity vectors // each frame. //mVelocityFromGravityAccumulator += (gravity * mTimeDelta); mVelocityFromGravityAccumulator += (gravity * mTimeDelta); //vprDEBUG_CONT(vprDBG_ALL,0) // << " new vel: " << velocityAccumulator // << " new grav: " << mVelocityFromGravityAccumulator << std::endl // << vprDEBUG_FLUSH; } if (mAllowTrans) { // add velocity with respect to the tracking/pointing device velocityAccumulator += (trackerZaxis * mVelocity[2]); // forward/reverse |reletive to tracker velocityAccumulator += (trackerXaxis * mVelocity[0]); // strafe |reletive to tracker velocityAccumulator += (trackerYaxis * mVelocity[1]); // rise/dive |reletive to tracker } // Get rid of some velocity due to damping in the system mVelocity -= (mVelocity * (1.0f - mDamping)); // navigation just calculated navigator's next velocity // now convert accumulated velocity to distance traveled this frame (by // cancelling out time) // NOTE: this is not the final distance, since we still have to do // collision correction. gmtl::Vec3f distanceToMove = velocityAccumulator * mTimeDelta; //vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL) // << "velNav: distToMove = velAcum * instant: " << velocityAccumulator // << " * " << mTimeDelta << std::endl << vprDEBUG_FLUSH; // --- TRANSLATION and COLLISION DETECTION --- // bool did_collide; // Did we collide with anything // The total correction on the movement (in modelspace) gmtl::Vec3f total_correction; navTranslate(distanceToMove,did_collide,total_correction); if(did_collide) // If we hit something, stop falling { //vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL) // << "Did collide: Setting gravAccum to 0,0,0\n" // << vprDEBUG_FLUSH; mVelocityFromGravityAccumulator.set(0.0f, 0.0f, 0.0f); } //vprDEBUG_END(vprDBG_ALL,0) << "---------------------\n" << vprDEBUG_FLUSH; }
int WorldSocket::HandlePing(WorldPacket& recvPacket) { uint32 ping; uint32 latency; // Get the ping packet content recvPacket >> ping; recvPacket >> latency; if (m_LastPingTime == ACE_Time_Value::zero) m_LastPingTime = ACE_OS::gettimeofday(); // for 1st ping else { ACE_Time_Value cur_time = ACE_OS::gettimeofday(); ACE_Time_Value diff_time(cur_time); diff_time -= m_LastPingTime; m_LastPingTime = cur_time; if (diff_time < ACE_Time_Value(27)) { ++m_OverSpeedPings; uint32 max_count = sWorld.getConfig(CONFIG_UINT32_MAX_OVERSPEED_PINGS); if (max_count && m_OverSpeedPings > max_count) { ACE_GUARD_RETURN(LockType, Guard, m_SessionLock, -1); if (m_Session && m_Session->GetSecurity() == SEC_PLAYER) { sLog.outError("WorldSocket::HandlePing: Player kicked for " "overspeeded pings address = %s", GetRemoteAddress().c_str()); return -1; } } } else m_OverSpeedPings = 0; } // critical section { ACE_GUARD_RETURN(LockType, Guard, m_SessionLock, -1); if (m_Session) m_Session->SetLatency(latency); else { sLog.outError("WorldSocket::HandlePing: peer sent CMSG_PING, " "but is not authenticated or got recently kicked," " address = %s", GetRemoteAddress().c_str()); return -1; } } WorldPacket packet(SMSG_PONG, 4); packet << ping; return SendPacket(packet); }
void restart_prep(int restartee, int restarter) { int i; #ifdef TIME_RESTART_REPLICA timestamp_t start_restart = generate_timestamp(); #endif // TIME_RESTART_REPLICA // Normally the pipes are stolen, then written back. // Here, we want to fill the pipes to test the impact of large messages. // So we will write to them, and then steal them (so that the fake data isn't processed). // But probably won't work if real data is there... // Problem: normally steal once, write twice. Need a second write... use restarted rep? #ifdef PIPE_SMASH char pipe_fill[PIPE_FILL_SIZE] = {1}; for (i = 0; i < PIPE_LIMIT; i++) { if (replicas[restarter].vot_pipes[i].fd_out != 0) { writeBuffer(replicas[restarter].vot_pipes[i].fd_out, pipe_fill, sizeof(pipe_fill)); } } #endif // PIPE_SMASH char **restarter_buffer = (char **)malloc(sizeof(char *) * PIPE_LIMIT); if (restarter_buffer == NULL) { perror("Voter failed to malloc memory"); } for (i = 0; i < PIPE_LIMIT; i++) { restarter_buffer[i] = (char *)malloc(sizeof(char) * MAX_VOTE_PIPE_BUFF); if (restarter_buffer[i] == NULL) { perror("Voter failed to allocat memory"); } } int restarter_buff_count[PIPE_LIMIT] = {0}; // Steal the pipes from healthy reps. This stops them from processing mid restart (also need to copy data to new rep) stealPipes(restarter, restarter_buffer, restarter_buff_count); // reset timer timer_started = false; restartReplica(replicas, rep_count, &sd, ext_pipes, restarter, restartee, replica_priority); for (i = 0; i < replicas[restarter].pipe_count; i++) { if (replicas[restarter].vot_pipes[i].fd_in != 0) { copyPipe(&(replicas[restartee].vot_pipes[i]), &(replicas[restarter].vot_pipes[i])); sendPipe(i, restarter); // TODO: Need to check if available? } } #ifndef PIPE_SMASH // Give the buffers back returnPipes(restartee, restarter_buffer, restarter_buff_count); returnPipes(restarter, restarter_buffer, restarter_buff_count); // free the buffers for (i = 0; i < PIPE_LIMIT; i++) { free(restarter_buffer[i]); } free(restarter_buffer); #endif // !PIPE_SMASH // The second write #ifdef PIPE_SMASH for (i = 0; i < PIPE_LIMIT; i++) { if (replicas[restarter].vot_pipes[i].fd_out != 0) { writeBuffer(replicas[restarter].vot_pipes[i].fd_out, pipe_fill, sizeof(pipe_fill)); } } #endif // PIPE_SMASH #ifdef TIME_RESTART_REPLICA timestamp_t end_restart = generate_timestamp(); printf("Restart time elapsed usec (%lf)\n", diff_time(end_restart, start_restart, CPU_MHZ)); #endif // TIME_RESTART_REPLICA // Clean up by stealing the extra write. Not timed. #ifdef PIPE_SMASH if (restarter_buffer == NULL) { perror("Voter failed to malloc memory"); } for (i = 0; i < PIPE_LIMIT; i++) { restarter_buffer[i] = (char *)malloc(sizeof(char) * MAX_VOTE_PIPE_BUFF); if (restarter_buffer[i] == NULL) { perror("Voter failed to allocat memory"); } } stealPipes(restarter, restarter_buffer, restarter_buff_count); // free the buffers for (i = 0; i < PIPE_LIMIT; i++) { free(restarter_buffer[i]); } free(restarter_buffer); #endif // PIPE_SMASH return; }
//MAIN int main(int argc, char **argv) { //mtrace();//to check memory leakage problems //Initialize prev_rusage with 0 values struct rusage prev_rusage; getrusage(RUSAGE_CHILDREN,&prev_rusage); char str[129];//input string char* cmd_args[32]; //vector of strings (arguments for the shell) while(1) { printf(">");//prompt character if(fgets(str,129,stdin)==NULL)//EOF or error (to be able to pipe input files) break; //TODO: check string size int n_args = args_from_str(str, cmd_args); //Special cases if(n_args==0) {free_args(cmd_args); continue;}//no argument if(strcmp(cmd_args[0],"exit") == 0 && n_args == 1) {free_args(cmd_args); break;}//exit command if(strcmp(cmd_args[0],"cd") == 0) {//change directory built in command if(n_args==1)chdir("/home");//default value (in this case, the current directory) else chdir(cmd_args[1]); free_args(cmd_args); continue; } struct timeval init, end; //checkpoint to measure wall-clock time gettimeofday(&init,NULL);//get time right before creating the child pid_t pid = fork(); //create a new process //CHILD if (pid == 0) { if(execvp(cmd_args[0], cmd_args) == -1){ //error with de command perror(NULL);//print error message //free_args(cmd_args);//free memory allocaded in args_from_cmdline function exit(EXIT_FAILURE); } }else if (pid > 0) { //PARENT int status = 0;//return from wait function wait(&status);//wait for child execution gettimeofday(&end,NULL); free_args(cmd_args);//free memory allocaded in args_from_str function //if the child returned EXIT_FAILURE (when something goes wrong) if(WEXITSTATUS(status) == EXIT_FAILURE) { //the child print the error continue; //exit(EXIT_FAILURE); } //get CHILDREN execution statistics struct rusage current_rusage; getrusage(RUSAGE_CHILDREN,¤t_rusage); //Print report printf("\n***REPORT***\n"); printf("wall-clock:\t\t%d\n",diff_time(init,end)); //use the difference to get the measurements of the most recent child print_rusage(diff_rusage(current_rusage, prev_rusage)); prev_rusage = current_rusage;//update previous accumulated rusage }else { //error perror(NULL);//error in fork free_args(cmd_args);//free memory allocaded in args_from_str function exit(EXIT_FAILURE); } } //free_args(cmd_args);//free memory allocaded in args_from_str function return 0; }
void doOneUpdate(void) { int p_index, r_index; int retval = 0; struct timeval select_timeout; fd_set select_set; if (rep_type == SMR) { // Detect replica that self-kills, has no timer (Load does this due to memory leak) #ifdef TIME_WAITPID timestamp_t start_restart = generate_timestamp(); #endif // TIME_WAITPID // can only waitpid for children (unless subreaper is used (prctl is not POSIX compliant)). int exit_pid = waitpid(-1, NULL, WNOHANG); // Seems to take a while for to clean up zombies #ifdef TIME_WAITPID timestamp_t end_restart = generate_timestamp(); if (exit_pid > 0 && exit_pid != last_dead) { printf("Waitpid for %d (%s) took usec (%lf)\n", exit_pid, REP_TYPE_T[rep_type], diff_time(end_restart, start_restart, CPU_MHZ)); } else { //printf("No zombie took (%lld)\n", end_restart - start_restart); } #endif // TIME_WAITPID if (exit_pid > 0 && exit_pid != last_dead) { debug_print("PID %d exited on its own.\n", exit_pid); voterRestartHandler(); timer_started = false; } } select_timeout.tv_sec = 0; select_timeout.tv_usec = 50000; if (timer_started) { timestamp_t current = generate_timestamp(); long remaining = voting_timeout - diff_time(current, watchdog, CPU_MHZ); if (remaining > 0) { select_timeout.tv_sec = 0; select_timeout.tv_usec = remaining; } else { // printf("Restart handler called, %s is %ld late\n", controller_name, remaining); voterRestartHandler(); } } // See if any of the read pipes have anything FD_ZERO(&select_set); // Check external in pipes bool check_inputs = checkSync(); if (check_inputs) { for (p_index = 0; p_index < pipe_count; p_index++) { if (ext_pipes[p_index].fd_in != 0) { int e_pipe_fd = ext_pipes[p_index].fd_in; FD_SET(e_pipe_fd, &select_set); } } } else if (voter_priority < 5 && ! timer_started) { // non-RT controller is now lagging behind. timer_started = true; watchdog = generate_timestamp(); } // Check pipes from replicas for (p_index = 0; p_index < pipe_count; p_index++) { for (r_index = 0; r_index < rep_count; r_index++) { int rep_pipe_fd = replicas[r_index].vot_pipes[p_index].fd_in; if (rep_pipe_fd != 0) { FD_SET(rep_pipe_fd, &select_set); } } } // This will wait at least timeout until return. Returns earlier if something has data. retval = select(FD_SETSIZE, &select_set, NULL, NULL, &select_timeout); if (retval > 0) { // Check for data from external sources for (p_index = 0; p_index < pipe_count; p_index++) { int read_fd = ext_pipes[p_index].fd_in; if (read_fd != 0) { if (FD_ISSET(read_fd, &select_set)) { ext_pipes[p_index].buff_count = TEMP_FAILURE_RETRY(read(read_fd, ext_pipes[p_index].buffer, MAX_VOTE_PIPE_BUFF)); if (ext_pipes[p_index].buff_count > 0) { // TODO: read may still have been interrupted processData(&(ext_pipes[p_index]), p_index); } else if (ext_pipes[p_index].buff_count < 0) { printf("Voter - Controller %s pipe %d\n", controller_name, p_index); perror("Voter - read error on external pipe"); } else { printf("Voter - Controller %s pipe %d\n", controller_name, p_index); perror("Voter - read == 0 on external pipe"); } } } } // Check all replicas for data for (p_index = 0; p_index < pipe_count; p_index++) { for (r_index = 0; r_index < rep_count; r_index++) { struct vote_pipe* curr_pipe = &(replicas[r_index].vot_pipes[p_index]); if (curr_pipe->fd_in !=0) { if (FD_ISSET(curr_pipe->fd_in, &select_set)) { processFromRep(r_index, p_index); } } } } } }
void play_client(config cfg) { //time of the last step that occured. in ticks. int ok; //signal we're waiting for before begining char c; //key that is pressed int ret; //value returned by 'read(0)', 0 if no new key was pressed int ret_serv; queue p1_queue = new_queue(MAX_INPUT_STACK); //queue used to stack player input direction cur_dir; direction* players_dir = malloc(cfg.nb_players*sizeof(direction)); //let's wait for server's signal ret_serv = read(sockfd, &ok, 1*sizeof(int)); if(ret_serv < 0){ perror("handle_server read waiting for signal"); } else if(ret_serv == 0){ printf("Server on socket %i closed connection.\n", sockfd); clear(); safe_quit(1); } if(ok != 1){ printf("Wrong signal recieved from server. Received %i.\n", ok); safe_quit(1); } printf("Signal received. Starting now\n"); //sleep(3); //GO clear(); mode_raw(1); //creating field field* map = new_field(WIDTH, HEIGHT); //creating snakes int i; snake** snakes = malloc(cfg.nb_players*sizeof(snake*)); for(i = 0; i < cfg.nb_players; i++){ snakes[i] = new_snake(T_SNAKE, cfg.size, i, map); } fflush(stdout); struct timeval last_step_time; gettimeofday(&last_step_time, NULL); struct timeval now; int elapsed_time; //elapsed time while(1){ //SUMMARY //1 - let's check if it's time to retrieve input //2 - let's retrieve and sort every input //3 - let's send the server our direction //4 - let's wait for server's directions //5 - let's make snakes move //6 - let's update last_step_time //-------------------------------------- //1 - let's check if it's time to retrieve input gettimeofday(&now, NULL); elapsed_time = diff_time(now, last_step_time); //time elapsed since last round. in ms. if(elapsed_time > TIME_STEP - PING){ //2 - let's retrieve and sort every input while((ret = read(0, &c, sizeof(char))) != 0){ if(ret == -1){ perror("read in 'play()'"); safe_quit(1); } if(c == C_QUIT){ mode_raw(0); clear(); free_queue(&p1_queue); free_all_client(map, snakes, cfg.nb_players); return; } else if(key_is_p1_dir(c)){ //if the key is a move key for player 1: if(! queue_full(&p1_queue)){ enqueue(&p1_queue, key_to_dir(c)); } } else{ //key pressed was a useless key. Do nothing. } } //3 - let's send the server our direction cur_dir = (! queue_empty(&p1_queue)) ? dequeue(&p1_queue) : snakes[cfg.id]->dir; cur_dir = (cur_dir == opposite(snakes[cfg.id]->dir)) ? snakes[cfg.id]->dir : cur_dir; if(write(sockfd, &cur_dir, 1*sizeof(direction)) < 0){ perror("handle_server write"); safe_quit(1); } switch(cur_dir){ case 0: write(2, "sent 0\n", 7*sizeof(char)); break; case 1: write(2, "sent 1\n", 7*sizeof(char)); break; case 2: write(2, "sent 2\n", 7*sizeof(char)); break; case 3: write(2, "sent 3\n", 7*sizeof(char)); break; } //4 - let's wait for server's directions ret_serv = read(sockfd, players_dir, cfg.nb_players*sizeof(direction)); if(ret_serv == -1){ perror("handle_server read"); safe_quit(1); } else if(ret_serv == 0){ clear(); printf("Server closed connection.\n"); safe_quit(1); } //5 - let's make snakes move for(i = 0; i<cfg.nb_players; i++){ if(players_dir[i] != 4){ //if the player is not dead (dir = 4 => dead player) move(snakes[i], players_dir[i], map); } } fflush(stdout); //6 - let's update last_step_time gettimeofday(&last_step_time, NULL); } else{ //sleep 90% of the remaining time usleep( (((TIME_STEP - PING) - elapsed_time) * 0.9) * 1000); } } }
/* **************************************************** Function that generates an ascii file. **************************************************** */ int make_ascii_file(char * filepath, long double size, int extension_num) { char buf[MY_BLOCK_SIZE], strerr[100]; long double written = 0.0; long double blocks_written=0; int num_seeks=0, turn =0, seeker=0; long double * frag_schedule_array; int is_garbage =0, j=0; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; int fd=0; long double num_blocks = ceill(size/MY_BLOCK_SIZE); double min_blocks_needed=0.0; int write_iter =0; if(is_garbage ==1) { buf[0]='I'; buf[1]='M'; buf[2]='P'; buf[3]='R'; buf[4]='E'; buf[5]='S'; buf[6]='S'; } // get data buffer once for non word-freq __Ntime gettimeofday(&filecontent_start, NULL); random_word_block(buf); __Ntime gettimeofday(&filecontent_end, NULL); __Ntime filecontent_total += diff_time(filecontent_start, filecontent_end); if(IMP_input->Layoutscore < 1) { double fragment_degree = 1 - IMP_input->Layoutscore; min_blocks_needed = (double) ceil(1/fragment_degree); if(num_blocks>= min_blocks_needed) { num_seeks = (int) ((fragment_degree*num_blocks -floor(fragment_degree*num_blocks) <= 0.5) ? \ floor(fragment_degree*num_blocks):ceil(fragment_degree*num_blocks)); if(num_seeks!=0){ frag_schedule_array = (long double*) malloc(sizeof(long double)*num_seeks); #ifdef PRINT if(frag_schedule_array!=NULL) print_debug(0,"Allocated %d, numblocks %Lf, size %Lf\n", num_seeks, num_blocks, size); else print_debug(0,"Allocation error\n"); #endif } for(int i = 0; i < num_seeks; i++) { frag_schedule_array[i] = (long double) (rand()%((int)num_blocks) + 1); print_debug(0, " - %Lf -", frag_schedule_array[i]); } qsort((void*) frag_schedule_array, (size_t) num_seeks, (size_t) sizeof(long double), compfunc); #ifdef PRINT for(int j=0; j<num_seeks; j++) { print_debug(0," %Lf ", frag_schedule_array[j]); } #endif } } if((fd = pos_creat(filepath, mode)) <0) { strerror_r(errno, strerr, 100); print_debug(1,"Error: Unable to create file= %s %d\n", filepath, errno); } else { // write to file with size written = 0; // if filetype has a header, write it, e.g, PDF if (extension_num > 0){ written += (long double) pos_write(fd, (void*)extension_header[extension_num],sizeof(extension_header[extension_num])); } while(written < size) { // get new random block everytime for wordfreq, else we already got it once above if(IMP_input->Flag[sf_wordfreq] >=1) { __Ntime gettimeofday(&filecontent_start, NULL); random_word_block(buf); __Ntime gettimeofday(&filecontent_end, NULL); __Ntime filecontent_total += diff_time(filecontent_start, filecontent_end); } print_debug(0, "Write iteration %d\n", write_iter++); __Ntime gettimeofday(&file_creation_start, NULL); print_debug(0,"random block : %s\n", buf); if (size - written < MY_BLOCK_SIZE) { print_debug(0,"%s, %f, %f\n", filepath, size - written, size); written+=(long double)pos_write(fd,(void*)buf,(size_t)(size-written)); blocks_written+=1; // assumes previous pos_write wrote an entire block as issued print_debug(0,"Blocks to file %s,%f,%d\n",filepath,written,MY_BLOCK_SIZE); } else { written += (long double) pos_write(fd, (void*) buf, MY_BLOCK_SIZE); blocks_written+=1; // assumes previous pos_write wrote an entire block as issued print_debug(0,"Blocks to file %s, %f\n", filepath, written); } __Ntime gettimeofday(&file_creation_end, NULL); __Ntime file_creation_total += diff_time(file_creation_start, file_creation_end); /* Fragment the file in this loop */ __Ntime gettimeofday(&aging_start, NULL); if(num_seeks!=0 && seeker < num_seeks) { print_debug(0,"sch %Lf written %Lf\n", frag_schedule_array[seeker], blocks_written); while(frag_schedule_array[seeker]==frag_schedule_array[seeker+1]) seeker++; // throw away duplicates if(seeker < num_seeks && frag_schedule_array[seeker]==blocks_written) { fragment(turn); turn++; seeker++; } } __Ntime gettimeofday(&aging_end, NULL); __Ntime aging_total += diff_time(aging_start, aging_end); } //cleanup if(num_seeks > 0 && turn%2==1) fragment(-1); pos_close(fd); } if(num_seeks!=0) free(frag_schedule_array); }
/* **************************************************** Function that generates a binary file. **************************************************** */ int make_binary_file(char * filepath, long double size, int extension_num) { long double blocks_written=0; int num_seeks=0, turn =0, seeker=0; long double * frag_schedule_array; long double num_blocks = ceill(size/MY_BLOCK_SIZE); double min_blocks_needed=0.0; char buf[MY_BLOCK_SIZE], strerr[100]; long double written = 0.0; long double temp_write = 0.0; int is_garbage =0, j=0; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; FILE *fp; int write_iter =0; __Ntime gettimeofday(&filecontent_start, NULL); for(j=0; j< MY_BLOCK_SIZE; j++) { buf[j]= '\0'; } __Ntime gettimeofday(&filecontent_end, NULL); __Ntime filecontent_total += diff_time(filecontent_start, filecontent_end); if(is_garbage ==1) { buf[0]='I'; buf[1]='M'; buf[2]='P'; buf[3]='R'; buf[4]='E'; buf[5]='S'; buf[6]='S'; } if(IMP_input->Layoutscore < 1) { double fragment_degree = 1 - IMP_input->Layoutscore; min_blocks_needed = (double) ceil(1/fragment_degree); if(num_blocks>= min_blocks_needed) { num_seeks = (int) ((fragment_degree*num_blocks -floor(fragment_degree*num_blocks) <= 0.5) ? \ floor(fragment_degree*num_blocks):ceil(fragment_degree*num_blocks)); if(num_seeks!=0){ frag_schedule_array = (long double*) malloc(sizeof(long double)*num_seeks); #ifdef PRINT if(frag_schedule_array!=NULL) print_debug(0,"Allocated %d, numblocks %Lf, size %Lf\n", num_seeks, num_blocks, size); else print_debug(0,"Allocation error\n"); #endif } for(int i = 0; i < num_seeks; i++) { frag_schedule_array[i] = (long double) (rand()%((int)num_blocks) + 1); print_debug(0," - %Lf -", frag_schedule_array[i]); } qsort((void*) frag_schedule_array, (size_t) num_seeks, (size_t) sizeof(long double), compfunc); #ifdef PRINT for(int j=0; j<num_seeks; j++) { print_debug(0," %Lf ", frag_schedule_array[j]); } #endif } } if((fp = fopen(filepath,"wb"))==NULL ) { print_debug(0,"Error: Unable to create file= %s %d\n", filepath, errno); } else { // write to file with size written = 0; // if filetype has a header, write it, e.g, PDF if (extension_num > 0){ temp_write = (double) fwrite((void*)extension_header[extension_num], (size_t) (sizeof(extension_header[extension_num])),1, fp); written+=(long double) temp_write*sizeof(extension_header[extension_num]); } while(written < size) { print_debug(0, "Write iteration %d\n", write_iter++); __Ntime gettimeofday(&file_creation_start, NULL); if (size - written < MY_BLOCK_SIZE) { temp_write = (long double)fwrite((void*)buf,(size_t)(size-written), 1, fp); written+=temp_write*(size-written); } else { temp_write =(long double)fwrite((void*)buf,(size_t)(MY_BLOCK_SIZE), 1, fp); written+=temp_write*MY_BLOCK_SIZE; } __Ntime gettimeofday(&file_creation_end, NULL); __Ntime file_creation_total += diff_time(file_creation_start, file_creation_end); /* Fragment the file */ __Ntime gettimeofday(&aging_start, NULL); if(num_seeks!=0 && seeker < num_seeks) { #ifdef PRINT print_debug(0,"sch %Lf written %Lf\n", frag_schedule_array[seeker], blocks_written); #endif while(frag_schedule_array[seeker]==frag_schedule_array[seeker+1]) seeker++; // throw away duplicates if(seeker < num_seeks && frag_schedule_array[seeker]==blocks_written) { fragment(turn); turn++; seeker++; } } __Ntime gettimeofday(&aging_end, NULL); __Ntime aging_total += diff_time(aging_start, aging_end); } //cleanup if(num_seeks > 0 && turn%2==1) fragment(-1); fclose(fp); } if(num_seeks!=0) free(frag_schedule_array); }
/* **************************************************** Function that generates all files. **************************************************** */ long double make_generic_file(char * filepath, long double size, int depth, FILE * fp_log) { int header_size=0; char header[1024]; char ext[3], full_filepath[1024], helperexec[1024]; char cmd[1024], args[1024]; int ext_number; __Ntime gettimeofday(&extension_start, NULL); /* Either the extension is specified directly by the user, or one is chosen according to the count popularity */ if(IMP_input->Flag[sf_ext] >=0) ext_number = IMP_input->Flag[sf_ext]; else ext_number = montecarlo_extension(); __Ntime gettimeofday(&extension_end, NULL); __Ntime extension_total += diff_time(extension_start, extension_end); /* If the tail is chosen, generate a random extension */ if(ext_number == NUM_EXTENSIONS - 1 ) { get_random_ext(ext); print_debug(0, "Tail file selected %d %s\n", ext_number, ext); } else { strcpy(ext, extension_array[ext_number]); print_debug(0, "Non Tail file selected %d %s\n", ext_number, ext); } if(IMP_input->Printwhat[pw_ext]==1) { print_debug(0,"Extension: %s\n", ext); } if(ext_number) sprintf(full_filepath, "%s.%s", filepath, ext); //extension_array[ext_number]); else if (ext_number ==0) { sprintf(full_filepath, "%s", filepath); /*If you want a ".nul" instead of just a file without any extension, use the following line instead*/ //sprintf(full_filepath, "%s.%s", filepath, extension_array[ext_number]); } print_debug(0,"File: %s\n",full_filepath); if(ACTUAL_LOG_CREATION) { if(!fprintf(fp_log, "%s %d %Lf %d %s\n", ext, ext_number, size, depth, full_filepath)) print_debug(0,"LOG FILE from impress not being written!\n"); } /* If files and dirs are both being created on disk: Generate ascii, binary, or typed file according to file extension */ if(IMP_input->Actualfilecreation == 1) { switch(ext_number) { case NUL: case TXT: case CPP: case H: make_ascii_file(full_filepath, size, -1); break; case GIF: /* Create a gif file using the gif extension helper */ __Ntime gettimeofday(&file_creation_start, NULL); sprintf(helperexec, "%s/%s", EXT_HELPERS, "gif"); sprintf(cmd, "%s/%s %s %d %d", EXT_HELPERS, "gif", full_filepath, 1000, 1000); size = 1757; if(access(helperexec, X_OK) == 0) system(cmd); else { print_debug(0, "EXT_HELPER: gif not available, resorting to binary file\n"); make_binary_file(full_filepath, size, -1); } __Ntime gettimeofday(&file_creation_end, NULL); __Ntime file_creation_total += diff_time(file_creation_start, file_creation_end); break; case MP3: /* Create a mp3 file using the mp3 extension helper */ make_binary_file(full_filepath, size, -1); __Ntime gettimeofday(&file_creation_start, NULL); sprintf(args, "-a \"Test Artist\" -A \"Test Album\" -t \"Test Song Title\" -c \" Impressions File MP3\" -g \"POP\" -y \"2007\" -T \"1\""); sprintf(helperexec, "%s/%s", EXT_HELPERS, "mp3"); sprintf(cmd, "%s/%s %s %s",EXT_HELPERS, "mp3", args, full_filepath); if(access(helperexec, X_OK) == 0) system(cmd); else { print_debug(0, "EXT_HELPER: mp3 not available, resorting to binary file\n"); } __Ntime gettimeofday(&file_creation_end, NULL); __Ntime file_creation_total += diff_time(file_creation_start, file_creation_end); break; case LIB: case VHD: case EXE: case PDB: case DLL: case TAL: // tail file group, individual ext right now not factored make_binary_file(full_filepath, size, -1); // binary file break; case WMA: case PST: case PCH: // temporary solution, not creating a perfect PCH file make_binary_file(full_filepath, size, -1); // binary file break; case JPG: __Ntime gettimeofday(&file_creation_start, NULL); sprintf(helperexec, "%s/%s", EXT_HELPERS, "gif"); sprintf(cmd, "%s/%s %s %d %d", EXT_HELPERS, "gif", "temp.gif", 1000, 1000); size = 1757; if(access(helperexec, X_OK) == 0) { system(cmd); sprintf(cmd, "giftopnm temp.gif > temp.pnm"); system(cmd); sprintf(cmd, "pnmtojpeg temp.pnm > %s", full_filepath); system(cmd); } else { print_debug(0, "EXT_HELPER: gif not available, resorting to binary file\n"); make_binary_file(full_filepath, size, -1); } __Ntime gettimeofday(&file_creation_end, NULL); __Ntime file_creation_total += diff_time(file_creation_start, file_creation_end); break; case PDF: make_binary_file(full_filepath, size, 16); break; case HTM: make_ascii_file(full_filepath, size, -1); } } return size; }