int SDL_main(int argc, char** argv) { #else int main(int argc, char** argv) { #endif uint32_t windowFlags = 0; SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GLContext glContext = nullptr; #if defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_IOS) // For Android/iOS we need to set up for OpenGL ES and we make the window hi res & full screen SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_BORDERLESS | SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_ALLOW_HIGHDPI; #else // For all other clients we use the core profile and operate in a window SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; #endif static const int kStencilBits = 8; // Skia needs 8 stencil bits SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, kStencilBits); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); // If you want multisampling, uncomment the below lines and set a sample count static const int kMsaaSampleCount = 0; //4; // SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); // SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, kMsaaSampleCount); /* * In a real application you might want to initialize more subsystems */ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { handle_error(); return 1; } // Setup window // This code will create a window with the same resolution as the user's desktop. SDL_DisplayMode dm; if (SDL_GetDesktopDisplayMode(0, &dm) != 0) { handle_error(); return 1; } SDL_Window* window = SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, dm.w, dm.h, windowFlags); if (!window) { handle_error(); return 1; } // To go fullscreen // SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); // try and setup a GL context glContext = SDL_GL_CreateContext(window); if (!glContext) { handle_error(); return 1; } int success = SDL_GL_MakeCurrent(window, glContext); if (success != 0) { handle_error(); return success; } uint32_t windowFormat = SDL_GetWindowPixelFormat(window); int contextType; SDL_GL_GetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, &contextType); int dw, dh; SDL_GL_GetDrawableSize(window, &dw, &dh); glViewport(0, 0, dw, dh); glClearColor(1, 1, 1, 1); glClearStencil(0); glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // setup GrContext auto interface = GrGLMakeNativeInterface(); // setup contexts sk_sp<GrContext> grContext(GrContext::MakeGL(interface)); SkASSERT(grContext); // Wrap the frame buffer object attached to the screen in a Skia render target so Skia can // render to it GrGLint buffer; GR_GL_GetIntegerv(interface.get(), GR_GL_FRAMEBUFFER_BINDING, &buffer); GrGLFramebufferInfo info; info.fFBOID = (GrGLuint) buffer; SkColorType colorType; //SkDebugf("%s", SDL_GetPixelFormatName(windowFormat)); // TODO: the windowFormat is never any of these? if (SDL_PIXELFORMAT_RGBA8888 == windowFormat) { info.fFormat = GR_GL_RGBA8; colorType = kRGBA_8888_SkColorType; } else { colorType = kBGRA_8888_SkColorType; if (SDL_GL_CONTEXT_PROFILE_ES == contextType) { info.fFormat = GR_GL_BGRA8; } else { // We assume the internal format is RGBA8 on desktop GL info.fFormat = GR_GL_RGBA8; } } GrBackendRenderTarget target(dw, dh, kMsaaSampleCount, kStencilBits, info); // setup SkSurface // To use distance field text, use commented out SkSurfaceProps instead // SkSurfaceProps props(SkSurfaceProps::kUseDeviceIndependentFonts_Flag, // SkSurfaceProps::kLegacyFontHost_InitType); SkSurfaceProps props(SkSurfaceProps::kLegacyFontHost_InitType); sk_sp<SkSurface> surface(SkSurface::MakeFromBackendRenderTarget(grContext.get(), target, kBottomLeft_GrSurfaceOrigin, colorType, nullptr, &props)); SkCanvas* canvas = surface->getCanvas(); canvas->scale((float)dw/dm.w, (float)dh/dm.h); ApplicationState state; const char* helpMessage = "Click and drag to create rects. Press esc to quit."; SkPaint paint; // create a surface for CPU rasterization sk_sp<SkSurface> cpuSurface(SkSurface::MakeRaster(canvas->imageInfo())); SkCanvas* offscreen = cpuSurface->getCanvas(); offscreen->save(); offscreen->translate(50.0f, 50.0f); offscreen->drawPath(create_star(), paint); offscreen->restore(); sk_sp<SkImage> image = cpuSurface->makeImageSnapshot(); int rotation = 0; SkFont font; while (!state.fQuit) { // Our application loop SkRandom rand; canvas->clear(SK_ColorWHITE); handle_events(&state, canvas); paint.setColor(SK_ColorBLACK); canvas->drawString(helpMessage, 100.0f, 100.0f, font, paint); for (int i = 0; i < state.fRects.count(); i++) { paint.setColor(rand.nextU() | 0x44808080); canvas->drawRect(state.fRects[i], paint); } // draw offscreen canvas canvas->save(); canvas->translate(dm.w / 2.0, dm.h / 2.0); canvas->rotate(rotation++); canvas->drawImage(image, -50.0f, -50.0f); canvas->restore(); canvas->flush(); SDL_GL_SwapWindow(window); } if (glContext) { SDL_GL_DeleteContext(glContext); } //Destroy window SDL_DestroyWindow(window); //Quit SDL subsystems SDL_Quit(); return 0; }
TInt Cstif_3::stif_dbus_connection_return_message0( CStifItemParser& aItem ) { TestModuleIf().SetBehavior( CTestModuleIf::ETestLeaksRequests ); TestModuleIf().SetBehavior( CTestModuleIf::ETestLeaksHandles ); DBusConnection* connection; DBusError error; DBusMessage* msg; DBusMessage* borrow_message; DBusMessage* reply = NULL; char error_name[40]; char error_msg[40]; dbus_error_init(&error); connection = dbus_bus_get_private(DBUS_BUS_SESSION, &error); if(!connection) { sprintf(error_name, "Error_name : %s", error.name); iLog->Log(_L8(error_name)); sprintf(error_msg, "Error_msg : %s", error.message); iLog->Log(_L8(error_msg)); return 1; } msg = dbus_message_new_method_call("Test.Method.Call1", "/Test/Method/Object", "test.Method.Call", "dbus_connection_return_message0"); if(msg == NULL) { iLog->Log(_L8("message error")); return 1; } reply = dbus_connection_send_with_reply_and_block(connection, msg, 10000, &error); if(!reply) return handle_error(&error); iLog->Log(_L8("Reply Message is been received ")); borrow_message = dbus_connection_borrow_message (connection ) ; if(borrow_message== NULL) { iLog->Log(_L8("Queue is empty")); iLog->Log(_L8("Test case failed")); return 1; } else { dbus_connection_return_message(connection,borrow_message); iLog->Log(_L8("dbus_connection_return_message is executed succesfully")); iLog->Log( KSuccess ); dbus_message_unref(msg); dbus_connection_close(connection); dbus_connection_unref(connection); dbus_shutdown(); return KErrNone; } }
void tcp_data_handler::on_error(int fd) { handle_error(ERROR_TYPE_SYSTEM) ; }
int read_sock(int sock, char *data, int length){ int retcode = read(sock, data, length); handle_error(retcode, "read() Fehler", NO_EXIT); return retcode; }
int main(int argc, char *argv[]) { int s, tnum, opt, num_threads; struct thread_info *tinfo; pthread_attr_t attr; int stack_size; void *res; /* The "-s" option specifies a stack size for our threads */ stack_size = -1; while ((opt = getopt(argc, argv, "s:")) != -1) { switch (opt) { case 's': stack_size = strtoul(optarg, NULL, 0); break; default: fprintf(stderr, "Usage: %s [-s stack-size] arg...\n", argv[0]); exit(EXIT_FAILURE); } } num_threads = argc - optind; /* Initialize thread creation attributes */ s = pthread_attr_init(&attr); if (s != 0) handle_error_en(s, "pthread_attr_init"); if (stack_size > 0) { s = pthread_attr_setstacksize(&attr, stack_size); if (s != 0) handle_error_en(s, "pthread_attr_setstacksize"); } /* Allocate memory for pthread_create() arguments */ tinfo = calloc(num_threads, sizeof(struct thread_info)); if (tinfo == NULL) handle_error("calloc"); /* Create one thread for each command-line argument */ for (tnum = 0; tnum < num_threads; tnum++) { tinfo[tnum].thread_num = tnum + 1; tinfo[tnum].argv_string = argv[optind + tnum]; /* The pthread_create() call stores the thread ID into corresponding element of tinfo[] */ s = pthread_create(&tinfo[tnum].thread_id, &attr, &thread_start, &tinfo[tnum]); if (s != 0) handle_error_en(s, "pthread_create"); } /* Destroy the thread attributes object, since it is no longer needed */ s = pthread_attr_destroy(&attr); if (s != 0) handle_error_en(s, "pthread_attr_destroy"); /* Now join with each thread, and display its returned value */ for (tnum = 0; tnum < num_threads; tnum++) { s = pthread_join(tinfo[tnum].thread_id, &res); if (s != 0) handle_error_en(s, "pthread_join"); printf("Joined with thread %d; returned value was %s\n", tinfo[tnum].thread_num, (char *) res); free(res); /* Free memory allocated by thread */ } free(tinfo); exit(EXIT_SUCCESS); }
int do_selftest_decompression(void) { char *obuf, *ibuf, *workmem; FILE *ifile; int ret; long PAGE_SIZE = sysconf(_SC_PAGE_SIZE); uint32_t ilen = PAGE_SIZE + 100; uint32_t olen = csnappy_max_compressed_length(ilen); if (!(obuf = (char*)malloc(olen))) handle_error("malloc"); if (!(ibuf = (char*)malloc(ilen))) handle_error("malloc"); if (!(ifile = fopen("/dev/urandom", "rb"))) handle_error("fopen"); if (fread(ibuf, 1, ilen, ifile) < ilen) handle_error("fread"); if (fclose(ifile)) handle_error("fclose"); if (!(workmem = (char*)malloc(CSNAPPY_WORKMEM_BYTES))) handle_error("malloc"); csnappy_compress(ibuf, ilen, obuf, &olen, workmem, CSNAPPY_WORKMEM_BYTES_POWER_OF_TWO); free(workmem); free(ibuf); ibuf = obuf; ilen = olen; olen = PAGE_SIZE; obuf = (char*)mmap(NULL, PAGE_SIZE * 2, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (obuf == MAP_FAILED) handle_error("mmap"); if (mprotect(obuf + PAGE_SIZE, PAGE_SIZE, PROT_NONE)) handle_error("mprotect"); ret = csnappy_decompress(ibuf, ilen, obuf, olen); if (ret != CSNAPPY_E_OUTPUT_INSUF) { fprintf(stderr, "snappy_decompress returned %d.\n", ret); exit(EXIT_FAILURE); } ret = csnappy_decompress_noheader(ibuf + 2, ilen - 2, obuf, &olen); if (ret != CSNAPPY_E_OUTPUT_OVERRUN) { fprintf(stderr, "csnappy_decompress_noheader returned %d.\n", ret); exit(EXIT_FAILURE); } free(ibuf); if (munmap(obuf, PAGE_SIZE * 2)) handle_error("munmap"); olen = 50; if (!(obuf = (char*)malloc(olen))) handle_error("malloc"); ret = csnappy_decompress(fake, 9, obuf, olen); if (ret == CSNAPPY_E_OK) { fprintf(stderr, "csnappy_decompress, stream cut off mid literal: %d\n", ret); exit(EXIT_FAILURE); } ret = csnappy_decompress_noheader(fake + 1, 8, obuf, &olen); if (ret == CSNAPPY_E_OK) { fprintf(stderr, "csnappy_decompress_noheader, stream cut off mid literal: %d\n", ret); exit(EXIT_FAILURE); } free(obuf); return 0; }
extern "C" JNIEXPORT void JNICALL Java_com_intel_realsense_librealsense_FrameSet_nAddRef(JNIEnv *env, jclass type, jlong handle) { rs2_error *e = NULL; rs2_frame_add_ref((rs2_frame *) handle, &e); handle_error(env, e); }
int main(int argc, char **argv) { int *buf, i, rank, nints, len; char *filename, *tmp; int errs = 0, toterrs, errcode; MPI_File fh; MPI_Status status; MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); /* process 0 takes the file name as a command-line argument and broadcasts it to other processes */ if (!rank) { i = 1; while ((i < argc) && strcmp("-fname", *argv)) { i++; argv++; } if (i >= argc) { fprintf(stderr, "\n*# Usage: simple -fname filename\n\n"); MPI_Abort(MPI_COMM_WORLD, 1); } argv++; len = strlen(*argv); filename = (char *) malloc(len+10); strcpy(filename, *argv); MPI_Bcast(&len, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(filename, len+10, MPI_CHAR, 0, MPI_COMM_WORLD); } else { MPI_Bcast(&len, 1, MPI_INT, 0, MPI_COMM_WORLD); filename = (char *) malloc(len+10); MPI_Bcast(filename, len+10, MPI_CHAR, 0, MPI_COMM_WORLD); } buf = (int *) malloc(SIZE); nints = SIZE/sizeof(int); for (i=0; i<nints; i++) buf[i] = rank*100000 + i; /* each process opens a separate file called filename.'myrank' */ tmp = (char *) malloc(len+10); strcpy(tmp, filename); sprintf(filename, "%s.%d", tmp, rank); errcode = MPI_File_open(MPI_COMM_SELF, filename, MPI_MODE_CREATE | MPI_MODE_RDWR, MPI_INFO_NULL, &fh); if (errcode != MPI_SUCCESS) handle_error(errcode, "MPI_File_open(1)"); errcode = MPI_File_write(fh, buf, nints, MPI_INT, &status); if (errcode != MPI_SUCCESS) handle_error(errcode, "MPI_File_write"); errcode = MPI_File_close(&fh); if (errcode != MPI_SUCCESS) handle_error(errcode, "MPI_File_clode (1)"); /* reopen the file and read the data back */ for (i=0; i<nints; i++) buf[i] = 0; errcode = MPI_File_open(MPI_COMM_SELF, filename, MPI_MODE_CREATE | MPI_MODE_RDWR, MPI_INFO_NULL, &fh); if (errcode != MPI_SUCCESS) handle_error(errcode, "MPI_File_open(2)"); errcode = MPI_File_read(fh, buf, nints, MPI_INT, &status); if (errcode != MPI_SUCCESS) handle_error(errcode, "MPI_File_read"); errcode = MPI_File_close(&fh); if (errcode != MPI_SUCCESS) handle_error(errcode, "MPI_File_close(2)"); /* check if the data read is correct */ for (i=0; i<nints; i++) { if (buf[i] != (rank*100000 + i)) { errs++; fprintf(stderr, "Process %d: error, read %d, should be %d\n", rank, buf[i], rank*100000+i); } } MPI_Allreduce( &errs, &toterrs, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD ); if (rank == 0) { if( toterrs > 0) { fprintf( stderr, "Found %d errors\n", toterrs ); } else { fprintf( stdout, " No Errors\n" ); } } free(buf); free(filename); free(tmp); MPI_Finalize(); return 0; }
int main(int argc, char **argv) { int i = 0; int ret = 0; ssize_t nr_changes = 0; ssize_t changes = 0; char fbuf[PATH_MAX] = { 0, }; ret = gf_changelog_init(NULL); if (ret) { handle_error("Init failed"); goto out; } /* get changes for brick "/home/vshankar/export/yow/yow-1" */ ret = gf_changelog_register("/export/z1/zwoop", "/tmp/scratch", "/tmp/change.log", 9, 5); if (ret) { handle_error("register failed"); goto out; } while (1) { i = 0; nr_changes = gf_changelog_scan(); if (nr_changes < 0) { handle_error("scan(): "); break; } if (nr_changes == 0) goto next; printf("Got %ld changelog files\n", nr_changes); while ((changes = gf_changelog_next_change(fbuf, PATH_MAX)) > 0) { printf("changelog file [%d]: %s\n", ++i, fbuf); /* process changelog */ /* ... */ /* ... */ /* ... */ /* done processing */ ret = gf_changelog_done(fbuf); if (ret) handle_error("gf_changelog_done"); } if (changes == -1) handle_error("gf_changelog_next_change"); next: sleep(10); } out: return ret; }
int create_sem(key_t key, const int sem_size, const char *txt, const char *etxt, int flags) { int semaphore_id = semget(key, sem_size, flags | PERM); handle_error(semaphore_id, etxt, PROCESS_EXIT); return semaphore_id; }
int main (int argc, char **argv) { int err, ret; int ii, i; char buffer[MAX_BUF + 1]; char *session_data = NULL; char *session_id = NULL; size_t session_data_size; size_t session_id_size; fd_set rset; int maxfd; struct timeval tv; int user_term = 0; socket_st hd; gaa_parser (argc, argv); if (hostname == NULL) { fprintf (stderr, "No hostname given\n"); exit (1); } sockets_init (); #ifndef _WIN32 signal (SIGPIPE, SIG_IGN); #endif init_global_tls_stuff (); socket_open( &hd, hostname, service); socket_connect( &hd); hd.session = init_tls_session (hostname); if (starttls) goto after_handshake; for (i = 0; i < 2; i++) { if (i == 1) { hd.session = init_tls_session (hostname); gnutls_session_set_data (hd.session, session_data, session_data_size); free (session_data); } ret = do_handshake (&hd); if (ret < 0) { fprintf (stderr, "*** Handshake has failed\n"); gnutls_perror (ret); gnutls_deinit (hd.session); return 1; } else { printf ("- Handshake was completed\n"); if (gnutls_session_is_resumed (hd.session) != 0) printf ("*** This is a resumed session\n"); } if (resume != 0 && i == 0) { gnutls_session_get_data (hd.session, NULL, &session_data_size); session_data = malloc (session_data_size); gnutls_session_get_data (hd.session, session_data, &session_data_size); gnutls_session_get_id (hd.session, NULL, &session_id_size); session_id = malloc (session_id_size); gnutls_session_get_id (hd.session, session_id, &session_id_size); /* print some information */ print_info (hd.session, hostname); printf ("- Disconnecting\n"); socket_bye (&hd); printf ("\n\n- Connecting again- trying to resume previous session\n"); socket_open( &hd, hostname, service); socket_connect(&hd); } else { break; } } after_handshake: printf ("\n- Simple Client Mode:\n\n"); #ifndef _WIN32 signal (SIGALRM, &starttls_alarm); #endif /* do not buffer */ #if !(defined _WIN32 || defined __WIN32__) setbuf (stdin, NULL); #endif setbuf (stdout, NULL); setbuf (stderr, NULL); for (;;) { if (starttls_alarmed && !hd.secure) { fprintf (stderr, "*** Starting TLS handshake\n"); ret = do_handshake (&hd); if (ret < 0) { fprintf (stderr, "*** Handshake has failed\n"); socket_bye (&hd); user_term = 1; break; } } FD_ZERO (&rset); FD_SET (fileno (stdin), &rset); FD_SET (hd.fd, &rset); maxfd = MAX (fileno (stdin), hd.fd); tv.tv_sec = 3; tv.tv_usec = 0; err = select (maxfd + 1, &rset, NULL, NULL, &tv); if (err < 0) continue; if (FD_ISSET (hd.fd, &rset)) { memset (buffer, 0, MAX_BUF + 1); ret = socket_recv (&hd, buffer, MAX_BUF); if (ret == 0) { printf ("- Peer has closed the GNUTLS connection\n"); break; } else if (handle_error (&hd, ret) < 0 && user_term == 0) { fprintf (stderr, "*** Server has terminated the connection abnormally.\n"); break; } else if (ret > 0) { if (verbose != 0) printf ("- Received[%d]: ", ret); for (ii = 0; ii < ret; ii++) { fputc (buffer[ii], stdout); } fflush (stdout); } if (user_term != 0) break; } if (FD_ISSET (fileno (stdin), &rset)) { if (fgets (buffer, MAX_BUF, stdin) == NULL) { if (hd.secure == 0) { fprintf (stderr, "*** Starting TLS handshake\n"); ret = do_handshake (&hd); if (ret < 0) { fprintf (stderr, "*** Handshake has failed\n"); socket_bye (&hd); user_term = 1; } } else { user_term = 1; break; } continue; } if (crlf != 0) { char *b = strchr (buffer, '\n'); if (b != NULL) strcpy (b, "\r\n"); } ret = socket_send (&hd, buffer, strlen (buffer)); if (ret > 0) { if (verbose != 0) printf ("- Sent: %d bytes\n", ret); } else handle_error (&hd, ret); } } if (user_term != 0) socket_bye (&hd); else gnutls_deinit (hd.session); #ifdef ENABLE_SRP gnutls_srp_free_client_credentials (srp_cred); #endif #ifdef ENABLE_PSK gnutls_psk_free_client_credentials (psk_cred); #endif gnutls_certificate_free_credentials (xcred); #ifdef ENABLE_ANON gnutls_anon_free_client_credentials (anon_cred); #endif gnutls_global_deinit (); return 0; }
int create_shm(key_t key, const char *txt, const char *etxt, int flags) { int shm_id = shmget(key, SIZE, flags | PERM); handle_error(shm_id, etxt, PROCESS_EXIT); return shm_id; }
int main(int argc, char *argv[]) { time_t t_start = time(NULL); if (is_help_requested(argc, argv)) { usage(argv[0], ""); } if (argc > 2) { usage(argv[0], "too many arguments"); } int retcode = 0; create_if_missing(REF_FILE, S_IRUSR | S_IWUSR); key_t shm_key = ftok(REF_FILE, 1); if (shm_key < 0) { handle_error(-1, "ftok failed", PROCESS_EXIT); } key_t sem_key = ftok(REF_FILE, 2); if (sem_key < 0) { handle_error(-1, "ftok failed", PROCESS_EXIT); } if (argc == 2 && strcmp(argv[1], "-s") == 0) { printf("setting up IPC\n"); int shm_id = create_shm(shm_key, "create", "shmget failed", IPC_CREAT); shmid_for_cleanup = shm_id; int semaphore_id = create_sem(sem_key, SEM_SIZE, "create", "semget (data) failed", IPC_CREAT); semid_for_cleanup = semaphore_id; show_sem_ctl(semaphore_id, 0, "semaphore before setup"); setup_sem(semaphore_id, "semaphore setup failed"); show_sem_ctl(semaphore_id, 0, "semaphore after setup"); printf("done\n"); exit(0); } int shm_id = create_shm(shm_key, "create", "shmget failed", 0); shmid_for_cleanup = shm_id; int semaphore_id = create_sem(sem_key, SEM_SIZE, "create", "semget failed", 0); semid_for_cleanup = semaphore_id; if (argc == 2 && strcmp(argv[1], "-c") == 0) { printf("cleaning up IPC\n"); cleanup(); exit(0); } char *name = ""; if (argc == 2) { name = argv[1]; } struct data *shm_data = (struct data *) shmat(shm_id, NULL, 0); time_t total_data_semops_wait = 0; char buffer[BUF_SIZE]; long *counter = shm_data->counter; while (TRUE) { ssize_t size_read = read(STDIN_FILENO, buffer, BUF_SIZE); if (size_read == 0) { /* end of file */ break; } handle_error(size_read, "error while reading stdin", PROCESS_EXIT); int i; for (i = 0; i < size_read; i++) { unsigned char c = buffer[i]; unsigned int ck = c % SEM_SIZE; struct sembuf semops_write; semops_write.sem_num = ck; semops_write.sem_op = -SEM_LIMIT; semops_write.sem_flg = SEM_UNDO; time_t t0 = time(NULL); // show_sem_ctl(semaphore_id, ck, "reserving write semaphore"); retcode = semop(semaphore_id, &semops_write, 1); handle_error(retcode, "error while getting write-semaphore", PROCESS_EXIT); // show_sem_ctl(semaphore_id, ck, "write semaphore reserved"); time_t dt = time(NULL) - t0; total_data_semops_wait += dt; counter[c]++; semops_write.sem_num = ck; semops_write.sem_op = SEM_LIMIT; semops_write.sem_flg = SEM_UNDO; // show_sem_ctl(semaphore_id, ck, "freeing write semaphore"); retcode = semop(semaphore_id, &semops_write, 1); handle_error(retcode, "error while releasing write-semaphore", PROCESS_EXIT); // show_sem_ctl(semaphore_id, ck, "write semaphore freed"); } } time_t total_duration = time(NULL) - t_start; unsigned int i; char output_buffer[16384]; char *output_ptr = output_buffer; int n; int m = 0; n = sprintf(output_ptr, "------------------------------------------------------------\n"); output_ptr += n; m += n; n = sprintf(output_ptr, "%s: pid=%ld\n", name, (long) getpid()); output_ptr += n; m += n; n = sprintf(output_ptr, "total wait for data: ~ %ld sec; total duration: ~ %ld\n", (long) total_data_semops_wait, (long) total_duration); output_ptr += n; m += n; n = sprintf(output_ptr, "------------------------------------------------------------\n"); output_ptr += n; m += n; for (i = 0; i < ALPHA_SIZE; i++) { struct sembuf semops_read; unsigned int ck = (i % SEM_SIZE); semops_read.sem_num = ck; semops_read.sem_op = -1; semops_read.sem_flg = SEM_UNDO; retcode = semop(semaphore_id, &semops_read, 1); handle_error(retcode, "error while getting read-semaphore", PROCESS_EXIT); long *counter = shm_data->counter; long val = counter[i]; semops_read.sem_op = 1; retcode = semop(semaphore_id, &semops_read, 1); handle_error(retcode, "error while releasing read-semaphore", PROCESS_EXIT); if (! (i & 007)) { n = sprintf(output_ptr, "\n"); output_ptr += n; m += n; } if ((i & 0177) < 32 || i == 127) { n = sprintf(output_ptr, "\\%03o: %10ld ", i, val); output_ptr += n; m += n; } else { n = sprintf(output_ptr, "%4c: %10ld ", (char) i, val); output_ptr += n; m += n; } } n = sprintf(output_ptr, "\n\n"); output_ptr += n; m += n; n = sprintf(output_ptr, "------------------------------------------------------------\n\n"); output_ptr += n; m += n; write(STDOUT_FILENO, output_buffer, (size_t) m); exit(0); }
int main(){ /************************************/ long_long checksum = 0; int i,j,k; for (i = 0; i < N; ++i) for (j = 0; j < N; ++j){ mul1[i][j]= (i+j) % 8 + 1; mul2[i][j]= (N-i+j) % 8 + 1; res[i][j] = 0; } /************************************/ int retval, EventSet=PAPI_NULL; long_long values[3]; long_long start_cycles, end_cycles, start_usec, end_usec; /* Initialize the PAPI library */ retval = PAPI_library_init(PAPI_VER_CURRENT); if (retval != PAPI_VER_CURRENT) { fprintf(stderr, "PAPI library init error!\n"); exit(1); } /* Create the Event Set */ if (PAPI_create_eventset(&EventSet) != PAPI_OK) handle_error(1, "create_eventset"); /* Add L1 data cache misses to the Event Set */ if (PAPI_add_event(EventSet,PAPI_L1_DCM) != PAPI_OK) handle_error(1,"add_event - L1_DCM"); /* Add load instructions completed to the Event Set */ if (PAPI_add_event(EventSet,PAPI_LD_INS) != PAPI_OK) handle_error(1,"add_event - LD_INS"); /* Add store instructions completed to the Event Set */ if (PAPI_add_event(EventSet,PAPI_SR_INS) != PAPI_OK) handle_error(1,"add_event - SR_INS"); /* Reset the counting events in the Event Set */ if (PAPI_reset(EventSet) != PAPI_OK) handle_error(1,"reset"); /* Read the counting of events in the Event Set */ if (PAPI_read(EventSet, values) != PAPI_OK) handle_error(1,"read"); printf("After resetting counter 'PAPI_L1_DCM' [x10^6]: %f\n", \ (double)(values[0])/1000000); printf("After resetting counter 'PAPI_LD_INS' [x10^6]: %f\n", \ (double)(values[1])/1000000); printf("After resetting counter 'PAPI_SR_INS' [x10^6]: %f\n", \ (double)(values[2])/1000000); /* Start counting events in the Event Set */ if (PAPI_start(EventSet) != PAPI_OK) handle_error(1,"start"); /* Gets the starting time in clock cycles */ start_cycles = PAPI_get_real_cyc(); /* Gets the starting time in microseconds */ start_usec = PAPI_get_real_usec(); /************************************/ /* MATRIX MULTIPLICATION */ /************************************/ for (i = 0; i < N; ++i) for (j = 0; j < N; ++j) for (k = 0; k < N; ++k) res[i][j] += mul1[i][k] * mul2[k][j]; /************************************/ /* Gets the ending time in clock cycles */ end_cycles = PAPI_get_real_cyc(); /* Gets the ending time in microseconds */ end_usec = PAPI_get_real_usec(); /* Stop the counting of events in the Event Set */ if (PAPI_stop(EventSet, values) != PAPI_OK) handle_error(1,"stop"); printf("After stopping counter 'PAPI_L1_DCM' [x10^6]: %f\n", \ (double)(values[0])/1000000); printf("After stopping counter 'PAPI_LD_INS' [x10^6]: %f\n", \ (double)(values[1])/1000000); printf("After stopping counter 'PAPI_SR_INS' [x10^6]: %f\n", \ (double)(values[2])/1000000); printf("Wall clock cycles [x10^6]: %f\n", \ (double)(end_cycles - start_cycles)/1000000); printf("Wall clock time [seconds]: %f\n", \ (double)(end_usec - start_usec)/1000000); for (i = 0; i < N; ++i) for (j = 0; j < N; ++j) checksum+=res[i][j]; printf("Matrix checksum: %lld\n", checksum); return(0); }
int main (int argc, char *argv[]) { RIG *my_rig; /* handle to rig (instance) */ rig_model_t my_model = RIG_MODEL_DUMMY; int retcode; /* generic return code from functions */ int verbose = 0; int show_conf = 0; int dump_caps_opt = 0; const char *rig_file=NULL, *ptt_file=NULL, *dcd_file=NULL; ptt_type_t ptt_type = RIG_PTT_NONE; dcd_type_t dcd_type = RIG_DCD_NONE; int serial_rate = 0; char *civaddr = NULL; /* NULL means no need to set conf */ char conf_parms[MAXCONFLEN] = ""; struct addrinfo hints, *result, *saved_result; int sock_listen; int reuseaddr = 1; char host[NI_MAXHOST]; char serv[NI_MAXSERV]; while(1) { int c; int option_index = 0; c = getopt_long (argc, argv, SHORT_OPTIONS, long_options, &option_index); if (c == -1) break; switch(c) { case 'h': usage(); exit(0); case 'V': version(); exit(0); case 'm': if (!optarg) { usage(); /* wrong arg count */ exit(1); } my_model = atoi(optarg); break; case 'r': if (!optarg) { usage(); /* wrong arg count */ exit(1); } rig_file = optarg; break; case 'p': if (!optarg) { usage(); /* wrong arg count */ exit(1); } ptt_file = optarg; break; case 'd': if (!optarg) { usage(); /* wrong arg count */ exit(1); } dcd_file = optarg; break; case 'P': if (!optarg) { usage(); /* wrong arg count */ exit(1); } if (!strcmp(optarg, "RIG")) ptt_type = RIG_PTT_RIG; else if (!strcmp(optarg, "DTR")) ptt_type = RIG_PTT_SERIAL_DTR; else if (!strcmp(optarg, "RTS")) ptt_type = RIG_PTT_SERIAL_RTS; else if (!strcmp(optarg, "PARALLEL")) ptt_type = RIG_PTT_PARALLEL; else if (!strcmp(optarg, "CM108")) ptt_type = RIG_PTT_CM108; else if (!strcmp(optarg, "NONE")) ptt_type = RIG_PTT_NONE; else ptt_type = atoi(optarg); break; case 'D': if (!optarg) { usage(); /* wrong arg count */ exit(1); } if (!strcmp(optarg, "RIG")) dcd_type = RIG_DCD_RIG; else if (!strcmp(optarg, "DSR")) dcd_type = RIG_DCD_SERIAL_DSR; else if (!strcmp(optarg, "CTS")) dcd_type = RIG_DCD_SERIAL_CTS; else if (!strcmp(optarg, "CD")) dcd_type = RIG_DCD_SERIAL_CAR; else if (!strcmp(optarg, "PARALLEL")) dcd_type = RIG_DCD_PARALLEL; else if (!strcmp(optarg, "NONE")) dcd_type = RIG_DCD_NONE; else dcd_type = atoi(optarg); break; case 'c': if (!optarg) { usage(); /* wrong arg count */ exit(1); } civaddr = optarg; break; case 's': if (!optarg) { usage(); /* wrong arg count */ exit(1); } serial_rate = atoi(optarg); break; case 'C': if (!optarg) { usage(); /* wrong arg count */ exit(1); } if (*conf_parms != '\0') strcat(conf_parms, ","); strncat(conf_parms, optarg, MAXCONFLEN-strlen(conf_parms)); break; case 't': if (!optarg) { usage(); /* wrong arg count */ exit(1); } portno = optarg; break; case 'T': if (!optarg) { usage(); /* wrong arg count */ exit(1); } src_addr = optarg; break; case 'o': vfo_mode++; break; case 'v': verbose++; break; case 'L': show_conf++; break; case 'l': list_models(); exit(0); case 'u': dump_caps_opt++; break; default: usage(); /* unknown option? */ exit(1); } } rig_set_debug(verbose); rig_debug(RIG_DEBUG_VERBOSE, "rigctld, %s\n", hamlib_version); rig_debug(RIG_DEBUG_VERBOSE, "Report bugs to " "<*****@*****.**>\n\n"); my_rig = rig_init(my_model); if (!my_rig) { fprintf(stderr, "Unknown rig num %d, or initialization error.\n", my_model); fprintf(stderr, "Please check with --list option.\n"); exit(2); } retcode = set_conf(my_rig, conf_parms); if (retcode != RIG_OK) { fprintf(stderr, "Config parameter error: %s\n", rigerror(retcode)); exit(2); } if (rig_file) strncpy(my_rig->state.rigport.pathname, rig_file, FILPATHLEN - 1); /* * ex: RIG_PTT_PARALLEL and /dev/parport0 */ if (ptt_type != RIG_PTT_NONE) my_rig->state.pttport.type.ptt = ptt_type; if (dcd_type != RIG_DCD_NONE) my_rig->state.dcdport.type.dcd = dcd_type; if (ptt_file) strncpy(my_rig->state.pttport.pathname, ptt_file, FILPATHLEN - 1); if (dcd_file) strncpy(my_rig->state.dcdport.pathname, dcd_file, FILPATHLEN - 1); /* FIXME: bound checking and port type == serial */ if (serial_rate != 0) my_rig->state.rigport.parm.serial.rate = serial_rate; if (civaddr) rig_set_conf(my_rig, rig_token_lookup(my_rig, "civaddr"), civaddr); /* * print out conf parameters */ if (show_conf) { rig_token_foreach(my_rig, print_conf_list, (rig_ptr_t)my_rig); } /* * print out conf parameters, and exits immediately * We may be interested only in only caps, and rig_open may fail. */ if (dump_caps_opt) { dumpcaps(my_rig, stdout); rig_cleanup(my_rig); /* if you care about memory */ exit(0); } retcode = rig_open(my_rig); if (retcode != RIG_OK) { fprintf(stderr,"rig_open: error = %s \n", rigerror(retcode)); exit(2); } if (verbose > 0) printf("Opened rig model %d, '%s'\n", my_rig->caps->rig_model, my_rig->caps->model_name); rig_debug(RIG_DEBUG_VERBOSE, "Backend version: %s, Status: %s\n", my_rig->caps->version, rig_strstatus(my_rig->caps->status)); #ifdef __MINGW32__ # ifndef SO_OPENTYPE # define SO_OPENTYPE 0x7008 # endif # ifndef SO_SYNCHRONOUS_NONALERT # define SO_SYNCHRONOUS_NONALERT 0x20 # endif # ifndef INVALID_SOCKET # define INVALID_SOCKET -1 # endif WSADATA wsadata; if (WSAStartup(MAKEWORD(1,1), &wsadata) == SOCKET_ERROR) { fprintf(stderr,"WSAStartup socket error\n"); exit(1); } int sockopt = SO_SYNCHRONOUS_NONALERT; setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&sockopt, sizeof(sockopt)); #endif /* * Prepare listening socket */ memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ hints.ai_socktype = SOCK_STREAM;/* TCP socket */ hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */ hints.ai_protocol = 0; /* Any protocol */ retcode = getaddrinfo(src_addr, portno, &hints, &result); if (retcode != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(retcode)); exit(2); } saved_result = result; do { sock_listen = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (sock_listen < 0) { handle_error (RIG_DEBUG_ERR, "socket"); freeaddrinfo(saved_result); /* No longer needed */ exit(2); } if (setsockopt(sock_listen, SOL_SOCKET, SO_REUSEADDR, (char *)&reuseaddr, sizeof(reuseaddr)) < 0) { handle_error (RIG_DEBUG_ERR, "setsockopt"); freeaddrinfo(saved_result); /* No longer needed */ exit (1); } #ifdef __MINGW32__ /* allow IPv4 mapped to IPv6 clients, MS default this to 1! */ sockopt = 0; if (setsockopt(sock_listen, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&sockopt, sizeof(sockopt)) < 0) { handle_error (RIG_DEBUG_ERR, "setsockopt"); freeaddrinfo(saved_result); /* No longer needed */ exit (1); } #endif if (0 == bind(sock_listen, result->ai_addr, result->ai_addrlen)) { break; } handle_error (RIG_DEBUG_WARN, "binding failed (trying next interface)"); #ifdef __MINGW32__ closesocket (sock_listen); #else close (sock_listen); #endif } while ((result = result->ai_next) != NULL); freeaddrinfo(saved_result); /* No longer needed */ if (NULL == result) { rig_debug(RIG_DEBUG_ERR, "bind error - no available interface\n"); exit (1); } if (listen(sock_listen, 4) < 0) { handle_error (RIG_DEBUG_ERR, "listening"); exit (1); } /* * main loop accepting connections */ do { #ifdef HAVE_PTHREAD pthread_t thread; pthread_attr_t attr; #endif struct handle_data *arg; arg = malloc(sizeof(struct handle_data)); if (!arg) { rig_debug(RIG_DEBUG_ERR, "malloc: %s\n", strerror(errno)); exit (1); } arg->rig = my_rig; arg->clilen = sizeof (arg->cli_addr); arg->sock = accept(sock_listen, (struct sockaddr *)&arg->cli_addr, &arg->clilen); if (arg->sock < 0) { handle_error (RIG_DEBUG_ERR, "accept"); break; } if ((retcode = getnameinfo ((struct sockaddr const *)&arg->cli_addr, arg->clilen, host, sizeof (host) , serv, sizeof (serv), NI_NOFQDN)) < 0) { rig_debug (RIG_DEBUG_WARN, "Peer lookup error: %s", gai_strerror (retcode)); } rig_debug(RIG_DEBUG_VERBOSE, "Connection opened from %s:%s\n", host, serv); #ifdef HAVE_PTHREAD pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); retcode = pthread_create(&thread, &attr, handle_socket, arg); if (retcode != 0) { rig_debug(RIG_DEBUG_ERR, "pthread_create: %s\n", strerror(retcode)); break; } #else handle_socket(arg); #endif } while (retcode == 0); rig_close(my_rig); /* close port */ rig_cleanup(my_rig); /* if you care about memory */ #ifdef __MINGW32__ WSACleanup(); #endif return 0; }
str SQLinitClient(Client c) { mvc *m; str schema; str msg = MAL_SUCCEED; backend *be; bstream *bfd = NULL; stream *fd = NULL; static int maybeupgrade = 1; #ifdef _SQL_SCENARIO_DEBUG mnstr_printf(GDKout, "#SQLinitClient\n"); #endif if (SQLinitialized == 0 && (msg = SQLprelude(NULL)) != MAL_SUCCEED) return msg; MT_lock_set(&sql_contextLock, "SQLinitClient"); /* * Based on the initialization return value we can prepare a SQLinit * string with all information needed to initialize the catalog * based on the mandatory scripts to be executed. */ if (sqlinit) { /* add sqlinit to the fdin stack */ buffer *b = (buffer *) GDKmalloc(sizeof(buffer)); size_t len = strlen(sqlinit); bstream *fdin; buffer_init(b, _STRDUP(sqlinit), len); fdin = bstream_create(buffer_rastream(b, "si"), b->len); bstream_next(fdin); MCpushClientInput(c, fdin, 0, ""); } if (c->sqlcontext == 0) { m = mvc_create(c->idx, 0, SQLdebug, c->fdin, c->fdout); global_variables(m, "monetdb", "sys"); if (isAdministrator(c) || strcmp(c->scenario, "msql") == 0) /* console should return everything */ m->reply_size = -1; be = (void *) backend_create(m, c); } else { be = c->sqlcontext; m = be->mvc; mvc_reset(m, c->fdin, c->fdout, SQLdebug, NR_GLOBAL_VARS); backend_reset(be); } if (m->session->tr) reset_functions(m->session->tr); /* pass through credentials of the user if not console */ schema = monet5_user_set_def_schema(m, c->user); if (!schema) { _DELETE(schema); throw(PERMD, "SQLinitClient", "08004!schema authorization error"); } _DELETE(schema); /*expect SQL text first */ be->language = 'S'; /* Set state, this indicates an initialized client scenario */ c->state[MAL_SCENARIO_READER] = c; c->state[MAL_SCENARIO_PARSER] = c; c->state[MAL_SCENARIO_OPTIMIZE] = c; c->sqlcontext = be; initSQLreferences(); /* initialize the database with predefined SQL functions */ if (SQLnewcatalog == 0) { /* check whether table sys.systemfunctions exists: if * it doesn't, this is probably a restart of the * server after an incomplete initialization */ sql_schema *s = mvc_bind_schema(m, "sys"); sql_table *t = s ? mvc_bind_table(m, s, "systemfunctions") : NULL; if (t == NULL) SQLnewcatalog = 1; } if (SQLnewcatalog > 0) { char path[PATHLENGTH]; str fullname; SQLnewcatalog = 0; maybeupgrade = 0; snprintf(path, PATHLENGTH, "createdb"); slash_2_dir_sep(path); fullname = MSP_locate_sqlscript(path, 1); if (fullname) { str filename = fullname; str p, n; fprintf(stdout, "# SQL catalog created, loading sql scripts once\n"); do { p = strchr(filename, PATH_SEP); if (p) *p = '\0'; if ((n = strrchr(filename, DIR_SEP)) == NULL) { n = filename; } else { n++; } fprintf(stdout, "# loading sql script: %s\n", n); fd = open_rastream(filename); if (p) filename = p + 1; if (fd) { size_t sz; sz = getFileSize(fd); if (sz > (size_t) 1 << 29) { mnstr_destroy(fd); msg = createException(MAL, "createdb", "file %s too large to process", filename); } else { bfd = bstream_create(fd, sz == 0 ? (size_t) (128 * BLOCK) : sz); if (bfd && bstream_next(bfd) >= 0) msg = SQLstatementIntern(c, &bfd->buf, "sql.init", TRUE, FALSE, NULL); bstream_destroy(bfd); } if (m->sa) sa_destroy(m->sa); m->sa = NULL; if (msg) p = NULL; } } while (p); GDKfree(fullname); } else fprintf(stderr, "!could not read createdb.sql\n"); } else { /* handle upgrades */ if (!m->sa) m->sa = sa_create(); if (maybeupgrade) SQLupgrades(c,m); maybeupgrade = 0; } MT_lock_unset(&sql_contextLock, "SQLinitClient"); fflush(stdout); fflush(stderr); /* send error from create scripts back to the first client */ if (msg) { error(c->fdout, msg); handle_error(m, c->fdout, 0); sqlcleanup(m, mvc_status(m)); } return msg; }
/*! Initializes the audio module. \author jfpatry \date Created: 2000-08-13 \date Modified: 2000-08-13 */ void init_audio() { int hz, channels, buffer; Uint16 format; check_assertion( !initialized_, "init_audio called twice" ); sound_contexts_ = create_hash_table(); music_contexts_ = create_hash_table(); initialized_ = True; /* * Init SDL Audio */ if ( getparam_no_audio() == False ) { if ( SDL_Init( SDL_INIT_AUDIO ) < 0 ) { handle_error( 1, "Couldn't initialize SDL: %s", SDL_GetError() ); } /* Open the audio device */ switch (getparam_audio_freq_mode()) { case 0: hz = 11025; break; case 1: hz = 22050; break; case 2: hz = 44100; break; default: hz = 22050; setparam_audio_freq_mode(1); } switch ( getparam_audio_format_mode() ) { case 0: format = AUDIO_U8; break; case 1: format = AUDIO_S16SYS; break; default: format = AUDIO_S16SYS; setparam_audio_format_mode( 1 ); } if ( getparam_audio_stereo() ) { channels = 2; } else { channels = 1; } buffer = getparam_audio_buffer_size(); if ( Mix_OpenAudio(hz, format, channels, buffer) < 0 ) { print_warning( 1, "Warning: Couldn't set %d Hz %d-bit audio\n" " Reason: %s\n", hz, getparam_audio_format_mode() == 0 ? 8 : 16, SDL_GetError()); } else { print_debug( DEBUG_SOUND, "Opened audio device at %d Hz %d-bit audio", hz, getparam_audio_format_mode() == 0 ? 8 : 16 ); } } }
str SQLparser(Client c) { bstream *in = c->fdin; stream *out = c->fdout; str msg = NULL; backend *be; mvc *m; int oldvtop, oldstop; int pstatus = 0; int err = 0, opt = 0; be = (backend *) c->sqlcontext; if (be == 0) { /* tell the client */ mnstr_printf(out, "!SQL state descriptor missing, aborting\n"); mnstr_flush(out); /* leave a message in the log */ fprintf(stderr, "SQL state descriptor missing, cannot handle client!\n"); /* stop here, instead of printing the exception below to the * client in an endless loop */ c->mode = FINISHCLIENT; throw(SQL, "SQLparser", "State descriptor missing"); } oldvtop = c->curprg->def->vtop; oldstop = c->curprg->def->stop; be->vtop = oldvtop; #ifdef _SQL_PARSER_DEBUG mnstr_printf(GDKout, "#SQL compilation \n"); printf("debugger? %d(%d)\n", (int) be->mvc->emode, (int) be->mvc->emod); #endif m = be->mvc; m->type = Q_PARSE; SQLtrans(m); pstatus = m->session->status; /* sqlparse needs sql allocator to be available. It can be NULL at * this point if this is a recursive call. */ if (!m->sa) m->sa = sa_create(); m->emode = m_normal; m->emod = mod_none; if (be->language == 'X') { int n = 0, v, off, len; if (strncmp(in->buf + in->pos, "export ", 7) == 0) n = sscanf(in->buf + in->pos + 7, "%d %d %d", &v, &off, &len); if (n == 2 || n == 3) { mvc_export_chunk(be, out, v, off, n == 3 ? len : m->reply_size); in->pos = in->len; /* HACK: should use parsed length */ return MAL_SUCCEED; } if (strncmp(in->buf + in->pos, "close ", 6) == 0) { res_table *t; v = (int) strtol(in->buf + in->pos + 6, NULL, 0); t = res_tables_find(m->results, v); if (t) m->results = res_tables_remove(m->results, t); in->pos = in->len; /* HACK: should use parsed length */ return MAL_SUCCEED; } if (strncmp(in->buf + in->pos, "release ", 8) == 0) { cq *q = NULL; v = (int) strtol(in->buf + in->pos + 8, NULL, 0); if ((q = qc_find(m->qc, v)) != NULL) qc_delete(m->qc, q); in->pos = in->len; /* HACK: should use parsed length */ return MAL_SUCCEED; } if (strncmp(in->buf + in->pos, "auto_commit ", 12) == 0) { int commit; v = (int) strtol(in->buf + in->pos + 12, NULL, 10); commit = (!m->session->auto_commit && v); m->session->auto_commit = (v) != 0; m->session->ac_on_commit = m->session->auto_commit; if (m->session->active) { if (commit && mvc_commit(m, 0, NULL) < 0) { mnstr_printf(out, "!COMMIT: commit failed while " "enabling auto_commit\n"); msg = createException(SQL, "SQLparser", "Xauto_commit (commit) failed"); } else if (!commit && mvc_rollback(m, 0, NULL) < 0) { RECYCLEdrop(0); mnstr_printf(out, "!COMMIT: rollback failed while " "disabling auto_commit\n"); msg = createException(SQL, "SQLparser", "Xauto_commit (rollback) failed"); } } in->pos = in->len; /* HACK: should use parsed length */ if (msg != NULL) goto finalize; return MAL_SUCCEED; } if (strncmp(in->buf + in->pos, "reply_size ", 11) == 0) { v = (int) strtol(in->buf + in->pos + 11, NULL, 10); if (v < -1) { msg = createException(SQL, "SQLparser", "reply_size cannot be negative"); goto finalize; } m->reply_size = v; in->pos = in->len; /* HACK: should use parsed length */ return MAL_SUCCEED; } if (strncmp(in->buf + in->pos, "sizeheader", 10) == 0) { v = (int) strtol(in->buf + in->pos + 10, NULL, 10); m->sizeheader = v != 0; in->pos = in->len; /* HACK: should use parsed length */ return MAL_SUCCEED; } if (strncmp(in->buf + in->pos, "quit", 4) == 0) { c->mode = FINISHCLIENT; return MAL_SUCCEED; } mnstr_printf(out, "!unrecognized X command: %s\n", in->buf + in->pos); msg = createException(SQL, "SQLparser", "unrecognized X command"); goto finalize; } if (be->language !='S') { mnstr_printf(out, "!unrecognized language prefix: %ci\n", be->language); msg = createException(SQL, "SQLparser", "unrecognized language prefix: %c", be->language); goto finalize; } if ((err = sqlparse(m)) || /* Only forget old errors on transaction boundaries */ (mvc_status(m) && m->type != Q_TRANS) || !m->sym) { if (!err &&m->scanner.started) /* repeat old errors, with a parsed query */ err = mvc_status(m); if (err) { msg = createException(PARSE, "SQLparser", "%s", m->errstr); handle_error(m, c->fdout, pstatus); } sqlcleanup(m, err); goto finalize; } assert(m->session->schema != NULL); /* * We have dealt with the first parsing step and advanced the input reader * to the next statement (if any). * Now is the time to also perform the semantic analysis, optimize and * produce code. */ be->q = NULL; if (m->emode == m_execute) { assert(m->sym->data.lval->h->type == type_int); be->q = qc_find(m->qc, m->sym->data.lval->h->data.i_val); if (!be->q) { err = -1; mnstr_printf(out, "!07003!EXEC: no prepared statement with id: %d\n", m->sym->data.lval->h->data.i_val); msg = createException(SQL, "PREPARE", "no prepared statement with id: %d", m->sym->data.lval->h->data.i_val); handle_error(m, c->fdout, pstatus); sqlcleanup(m, err); goto finalize; } else if (be->q->type != Q_PREPARE) { err = -1; mnstr_printf(out, "!07005!EXEC: given handle id is not for a " "prepared statement: %d\n", m->sym->data.lval->h->data.i_val); msg = createException(SQL, "PREPARE", "is not a prepared statement: %d", m->sym->data.lval->h->data.i_val); handle_error(m, c->fdout, pstatus); sqlcleanup(m, err); goto finalize; } m->emode = m_inplace; scanner_query_processed(&(m->scanner)); } else if (caching(m) && cachable(m, NULL) && m->emode != m_prepare && (be->q = qc_match(m->qc, m->sym, m->args, m->argc, m->scanner.key ^ m->session->schema->base.id)) != NULL) { // look for outdated plans if ( OPTmitosisPlanOverdue(c, be->q->name) ){ msg = SQLCacheRemove(c, be->q->name); qc_delete(be->mvc->qc, be->q); goto recompilequery; } if (m->emod & mod_debug) SQLsetDebugger(c, m, TRUE); if (m->emod & mod_trace) SQLsetTrace(be, c, TRUE); if (!(m->emod & (mod_explain | mod_debug | mod_trace | mod_dot))) m->emode = m_inplace; scanner_query_processed(&(m->scanner)); } else { sql_rel *r; stmt *s; recompilequery: r = sql_symbol2relation(m, m->sym); s = sql_relation2stmt(m, r); if (s == 0 || (err = mvc_status(m) && m->type != Q_TRANS)) { msg = createException(PARSE, "SQLparser", "%s", m->errstr); handle_error(m, c->fdout, pstatus); sqlcleanup(m, err); goto finalize; } assert(s); /* generate the MAL code */ if (m->emod & mod_trace) SQLsetTrace(be, c, TRUE); if (m->emod & mod_debug) SQLsetDebugger(c, m, TRUE); if (!caching(m) || !cachable(m, s)) { scanner_query_processed(&(m->scanner)); if (backend_callinline(be, c, s, 0) == 0) { opt = 1; } else { err = 1; } } else { /* generate a factory instantiation */ be->q = qc_insert(m->qc, m->sa, /* the allocator */ r, /* keep relational query */ m->sym, /* the sql symbol tree */ m->args, /* the argument list */ m->argc, m->scanner.key ^ m->session->schema->base.id, /* the statement hash key */ m->emode == m_prepare ? Q_PREPARE : m->type, /* the type of the statement */ sql_escape_str(QUERY(m->scanner))); scanner_query_processed(&(m->scanner)); be->q->code = (backend_code) backend_dumpproc(be, c, be->q, s); if (!be->q->code) err = 1; be->q->stk = 0; /* passed over to query cache, used during dumpproc */ m->sa = NULL; m->sym = NULL; /* register name in the namespace */ be->q->name = putName(be->q->name, strlen(be->q->name)); if (m->emode == m_normal && m->emod == mod_none) m->emode = m_inplace; } } if (err) m->session->status = -10; if (err == 0) { if (be->q) { if (m->emode == m_prepare) err = mvc_export_prepare(m, c->fdout, be->q, ""); else if (m->emode == m_inplace) { /* everything ready for a fast call */ } else { /* call procedure generation (only in cache mode) */ backend_call(be, c, be->q); } } /* In the final phase we add any debugging control */ if (m->emod & mod_trace) SQLsetTrace(be, c, FALSE); if (m->emod & mod_debug) SQLsetDebugger(c, m, FALSE); /* * During the execution of the query exceptions can be raised. * The default action is to print them out at the end of the * query block. */ pushEndInstruction(c->curprg->def); chkTypes(c->fdout, c->nspace, c->curprg->def, TRUE); /* resolve types */ if (opt) { MalBlkPtr mb = c->curprg->def; trimMalBlk(mb); chkProgram(c->fdout, c->nspace, mb); addOptimizers(c, mb, "default_pipe"); msg = optimizeMALBlock(c, mb); if (msg != MAL_SUCCEED) { sqlcleanup(m, err); goto finalize; } c->curprg->def = mb; } //printFunction(c->fdout, c->curprg->def, 0, LIST_MAL_ALL); /* we know more in this case than chkProgram(c->fdout, c->nspace, c->curprg->def); */ if (c->curprg->def->errors) { showErrors(c); /* restore the state */ MSresetInstructions(c->curprg->def, oldstop); freeVariables(c, c->curprg->def, c->glb, oldvtop); c->curprg->def->errors = 0; msg = createException(PARSE, "SQLparser", "Semantic errors"); } } finalize: if (msg) sqlcleanup(m, 0); return msg; }
int main(int argc, char **argv) { int i, j, k; int status; int ncid; int dimid1, dimid2, dimid3, udimid; int square_dim[2], cube_dim[3], xytime_dim[3], time_dim[1]; MPI_Offset square_start[2], cube_start[3] = {0, 0, 0}; MPI_Offset square_count[2] = {50, 50}, cube_count[3] = {100, 50, 50}; MPI_Offset square_stride[2] = {2, 2}; MPI_Offset xytime_start[3] = {0, 0, 0}; MPI_Offset xytime_count[3] = {100, 50, 50}; MPI_Offset time_start[1], time_count[1] = {25}; int square_id, cube_id, xytime_id, time_id; static char title[] = "example netCDF dataset"; static char description[] = "2-D integer array"; double data[100][50][50], buffer[100]; double stride_2d_data[50][50]; int rank; int nprocs; MPI_Comm comm = MPI_COMM_WORLD; params opts; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 0) fprintf(stderr, "Testing write ... "); parse_write_args(argc, argv, rank, &opts); /********** START OF NETCDF ACCESS **************/ /** * Create the dataset * File name: "testwrite.nc" * Dataset API: Collective */ status = ncmpi_create(comm, opts.outfname, NC_CLOBBER, MPI_INFO_NULL, &ncid); if (status != NC_NOERR) handle_error(status); /** * Create a global attribute: * :title = "example netCDF dataset"; */ status = ncmpi_put_att_text (ncid, NC_GLOBAL, "title", strlen(title), title); if (status != NC_NOERR) handle_error(status); /** * Add 4 pre-defined dimensions: * x = 100, y = 100, z = 100, time = NC_UNLIMITED */ status = ncmpi_def_dim(ncid, "x", 100L, &dimid1); if (status != NC_NOERR) handle_error(status); status = ncmpi_def_dim(ncid, "y", 100L, &dimid2); if (status != NC_NOERR) handle_error(status); status = ncmpi_def_dim(ncid, "z", 100L, &dimid3); if (status != NC_NOERR) handle_error(status); status = ncmpi_def_dim(ncid, "time", NC_UNLIMITED, &udimid); if (status != NC_NOERR) handle_error(status); /** * Define the dimensionality and then add 4 variables: * square(x, y), cube(x,y,z), time(time), xytime(time, x, y) */ square_dim[0] = cube_dim[0] = xytime_dim[1] = dimid1; square_dim[1] = cube_dim[1] = xytime_dim[2] = dimid2; cube_dim[2] = dimid3; xytime_dim[0] = udimid; time_dim[0] = udimid; status = ncmpi_def_var (ncid, "square", NC_DOUBLE, 2, square_dim, &square_id); if (status != NC_NOERR) handle_error(status); status = ncmpi_def_var (ncid, "cube", NC_DOUBLE, 3, cube_dim, &cube_id); if (status != NC_NOERR) handle_error(status); status = ncmpi_def_var (ncid, "time", NC_DOUBLE, 1, time_dim, &time_id); if (status != NC_NOERR) handle_error(status); status = ncmpi_def_var (ncid, "xytime", NC_DOUBLE, 3, xytime_dim, &xytime_id); if (status != NC_NOERR) handle_error(status); /** * Add an attribute for variable: * square: decsription = "2-D integer array" */ status = ncmpi_put_att_text (ncid, square_id, "description", strlen(description), description); if (status != NC_NOERR) handle_error(status); /** * End Define Mode (switch to data mode) * Dataset API: Collective */ status = ncmpi_enddef(ncid); if (status != NC_NOERR) handle_error(status); /** * Data Partition (Assume 4 processors): * square: 2-D, (Cyclic, Cyclic), 50*50 from 100*100, strided access * cube: 3-D, (*, Block, Block), 100*50*50 from 100*100*100 * xytime: 3-D, (*, Block, Block), 100*50*50 from 100*100*100 * time: 1-D, Block-wise, 25 from 100 */ /* square_start[0] = */ cube_start[1] = xytime_start[1] = (rank/2) * 50; /* square_start[1] = */ cube_start[2] = xytime_start[2] = (rank%2) * 50; time_start[0] = (rank%4) * 25; square_start[0] = rank/2; square_start[1] = rank%2; /** * Packing data in the buffer */ /* Data for variable: time */ for ( i = time_start[0]; i < time_start[0] + time_count[0]; i++ ) buffer[i - time_start[0]] = i; /* Data for variable: cube and xytime */ for ( i = 0; i < 100; i++ ) for ( j = cube_start[1]; j < cube_start[1]+cube_count[1]; j++ ) for ( k = cube_start[2]; k < cube_start[2]+cube_count[2]; k++ ) data[i][j-cube_start[1]][k-cube_start[2]] = i*100*100 + j*100 + k; /* Data for variable: square */ for ( i = 0; i < 50; i ++ ) for ( j = 0; j < 50; j++ ) stride_2d_data[i][j] = (2*i + rank/2)*100 + (2*j + rank%2); /** * Write data into variables: square, cube, time and xytime * Access Method: subarray * Data Mode API: collective */ status = ncmpi_put_vars_double_all(ncid, square_id, square_start, square_count, square_stride, &stride_2d_data[0][0]); if (status != NC_NOERR) handle_error(status); status = ncmpi_put_vara_double_all(ncid, cube_id, cube_start, cube_count, &data[0][0][0]); if (status != NC_NOERR) handle_error(status); status = ncmpi_put_vara_double_all(ncid, time_id, time_start, time_count, (void *)buffer); if (status != NC_NOERR) handle_error(status); status = ncmpi_put_vara_double_all(ncid, xytime_id, xytime_start, xytime_count, &data[0][0][0]); if (status != NC_NOERR) handle_error(status); /** * Close the dataset * Dataset API: collective */ status = ncmpi_close(ncid); if (status != NC_NOERR) handle_error(status); /******************* END OF NETCDF ACCESS ****************/ if (rank == 0) fprintf(stderr, "OK\nFile written to: %s!\n", opts.outfname); MPI_Finalize(); return 0; }
CURLcode curl_easy_perform(CURL *curl) { int rc; CURLcode err=CURLE_OK; const char *errstr=NULL; char *proxy=NULL; struct http_srv srv; memset(&srv,0,sizeof(srv)); /* Emulate the libcurl proxy behavior. If the calling program set a proxy, use it. If it didn't set a proxy or set it to NULL, check for one in the environment. If the calling program explicitly set a null-string proxy the http code doesn't use a proxy at all. */ if(curl->proxy) proxy=curl->proxy; else proxy=getenv(HTTP_PROXY_ENV); if(curl->srvtag) srv.srvtag=curl->srvtag; if(curl->flags.verbose) { fprintf(curl->errors,"* HTTP proxy is \"%s\"\n",proxy?proxy:"null"); fprintf(curl->errors,"* HTTP URL is \"%s\"\n",curl->url); if(srv.srvtag) fprintf(curl->errors, "* SRV tag is \"%s\": host and port may be overridden\n", srv.srvtag); fprintf(curl->errors,"* HTTP auth is \"%s\"\n", curl->auth?curl->auth:"null"); fprintf(curl->errors,"* HTTP method is %s\n", curl->flags.post?"POST":"GET"); } if(curl->flags.post) { rc=http_open(&curl->hd,HTTP_REQ_POST,curl->url,curl->auth,0,proxy, &srv,curl->headers?curl->headers->list:NULL); if(rc==0) { char content_len[50]; unsigned int post_len=strlen(curl->postfields); if(curl->flags.verbose && srv.used_server && srv.used_port) fprintf (curl->errors, "* HTTP host:port post-SRV is \"%s:%hu\"\n", srv.used_server, srv.used_port); iobuf_writestr(curl->hd.fp_write, "Content-Type: application/x-www-form-urlencoded\r\n"); sprintf(content_len,"Content-Length: %u\r\n",post_len); iobuf_writestr(curl->hd.fp_write,content_len); http_start_data(&curl->hd); iobuf_write(curl->hd.fp_write,curl->postfields,post_len); rc=http_wait_response(&curl->hd,&curl->status); if(rc==0 && curl->flags.failonerror && curl->status>=300) err=CURLE_HTTP_RETURNED_ERROR; } } else { rc=http_open(&curl->hd,HTTP_REQ_GET,curl->url,curl->auth,0,proxy, &srv,curl->headers?curl->headers->list:NULL); if(rc==0) { if(curl->flags.verbose && srv.used_server && srv.used_port) fprintf (curl->errors, "* HTTP host:port post-SRV is \"%s:%hu\"\n", srv.used_server, srv.used_port); rc=http_wait_response(&curl->hd,&curl->status); if(rc==0) { if(curl->flags.failonerror && curl->status>=300) err=CURLE_HTTP_RETURNED_ERROR; else { unsigned int maxlen=1024,buflen,len; byte *line=NULL; while((len=iobuf_read_line(curl->hd.fp_read, &line,&buflen,&maxlen))) { size_t ret; maxlen=1024; ret=(curl->writer)(line,len,1,curl->file); if(ret!=len) { err=CURLE_WRITE_ERROR; break; } } xfree(line); http_close(&curl->hd); } } else http_close(&curl->hd); } } free (srv.used_server); switch(rc) { case 0: break; case G10ERR_INVALID_URI: err=CURLE_UNSUPPORTED_PROTOCOL; break; case G10ERR_NETWORK: errstr=strerror(errno); err=CURLE_COULDNT_CONNECT; break; default: errstr=g10_errstr(rc); err=CURLE_COULDNT_CONNECT; break; } return handle_error(curl,err,errstr); }
void write_sock(int sock, char *data, int length){ int retcode = write(sock, data, length); handle_error(retcode, "write() Fehler", NO_EXIT); }
int read_matrix(char *matrixfile) { FILE *mfp; char numstr[FILENAME_LENGTH]; char line[INPUTMAX]; char *tmpstr; int i,j,k; int outsuitenum=0; int thisversion,thistest,faultvalue; int linelen, num_matches, line_num=0; /* Open the matrix file. */ mfp = fopen(matrixfile,"rt"); if(mfp == NULL) return handle_error( line_num, OPEN_FILE, mfp, matrixfile ); /* first line of the file hold number of versions */ tmpstr = fgets( line, INPUTMAX, mfp); line_num++; if( tmpstr == NULL ) return handle_error( line_num, NUM_VERS_A, mfp ); num_matches = sscanf( line, "%d", &numversions); if( num_matches != 1 ) return handle_error( line_num, NUM_VERS_B, mfp ); /* second line of the file hold number of tests */ tmpstr = fgets( line, INPUTMAX, mfp); line_num++; if (tmpstr == NULL) return handle_error( line_num, NUM_TESTS_A, mfp ); num_matches = sscanf( line, "%d", &numtests); if( num_matches != 1 ) return handle_error( line_num, NUM_TESTS_B, mfp ); if (numtests > MAXULINES) return handle_error( line_num, TOO_MANY, mfp ); /* now read numtests lines, each a universe file line, into the universe structure */ /* now read the lines */ for (i=0;i<numtests;i++) { tmpstr = fgets(line,INPUTMAX,mfp); line_num++; if(tmpstr == NULL) return handle_error(line_num, UNIVERSE_READ, mfp, i); /* for java subjects, CLASSPATH setting line is skipped */ if((line[0]=='C' && line[1]=='L' && line[2]=='A' && line[3]=='S' && line[4]=='S' && line[5]=='P' && line[6]=='A' && line[7]=='T' && line[8]=='H') || (line[0]=='s' && line[1]=='e' && line[2]=='t' && line[3]=='e' && line[4]=='n' && line[5]=='v')) { i = i - 1; } else { /* here malloc storage for and store the line */ linelen = strlen(line); if ((tmpstr = (char *) malloc((linelen+1)*sizeof(char *))) == NULL) return handle_error( line_num, UNIVERSE_MALLOC, mfp, i, linelen+1 ); strcpy(tmpstr,line); universe_lines[i] = tmpstr; } } /* now malloc the struct to hold the matrix */ if ((matrix = (int *)malloc(sizeof(int)*(numtests*numversions)))== NULL) return handle_error(line_num, MATRIX_MALLOC, mfp, numtests,numversions); /* now, for each test */ for (i=1;i<=numtests;i++) { /* get line and read test number from it */ tmpstr = fgets(line,INPUTMAX,mfp); line_num++; if (tmpstr == NULL) return handle_error( line_num, TEST_NUM_A, mfp, i ); num_matches = sscanf(line,"%*7s%d:",&thistest); if( num_matches != 1 ) return handle_error(line_num, TEST_NUM_B, mfp, i); /* now, for each version */ for (j=1;j<=numversions;j++) { /* get line and read version number from it */ tmpstr = fgets(line,INPUTMAX,mfp); line_num++; if ( tmpstr == NULL) return handle_error( line_num, VERS_NUM_A, mfp, thistest, i, j ); num_matches = sscanf(line,"%*1s%d:",&thisversion); if( num_matches != 1 ) return handle_error( line_num, VERS_NUM_B, mfp, thistest, i, j ); /* get line and read 0 or 1 from it */ tmpstr = fgets(line,INPUTMAX,mfp); line_num++; if(tmpstr == NULL) return handle_error(line_num,FAULT_VAL_A,mfp,thistest,thisversion); num_matches = sscanf(line,"%d",&faultvalue); if(num_matches!=1) return handle_error(line_num,FAULT_VAL_A,mfp,thistest,thisversion); /* fill in space in struct */ matrix[((thisversion -1)*numtests) + thistest] = faultvalue; #ifdef DEBUG printf("setting %d (%d,%d) to %d\n", ((thisversion-1)*numtests)+thistest, thisversion,thistest,faultvalue); #endif } } fclose(mfp); return TRUE; }
int main( int argc, char *argv[] ){ int sockfd, cfd, rec, s, wr=0, sent, lenn; int start = 0; char pcBuf[MAXBUF]; char fulBuf[MAXBUF]; int received; struct sockaddr client_addr; struct addrinfo hints; struct addrinfo *res; socklen_t client_addr_size; /******************* Connect to Client *******************/ /* struct setup*/ hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; s = getaddrinfo(NULL, argv[1], &hints, &res); if( s!=0){ fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); exit(EXIT_FAILURE); } /* create socket */ sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if( sockfd == -1) handle_error("socket"); /* bind the socket */ if( bind(sockfd, res->ai_addr, res->ai_addrlen) == -1) handle_error("bind"); /* listen for client */ if( listen(sockfd, LISTEN_BACKLOG) == -1) handle_error("listen"); freeaddrinfo(res); /* accept connection */ /* int accept(int sockfd, struct sockaddr *addr, socketlen_t *addrlen) */ client_addr_size = sizeof(struct sockaddr); while(1){ cfd = accept( sockfd, (struct sockaddr *) &client_addr, &client_addr_size); if( cfd <= 0) handle_error("accept"); /*receive GET request from client */ received= recv(cfd, pcBuf, MAXBUF, 0); int recc= recv(cfd, pcBuf+received, MAXBUF, 0); if(received == -1) fprintf(stderr, "recv: failed"); /*print received GET request on server terminal*/ if(write(1, pcBuf, received+recc) == -1){ handle_error("write"); } /* echo what was received from the client */ if((sent = send(cfd,pcBuf, received, 0)) <0) handle_error("send"); /******************* Parse Request From Client *******************/ int len = strlen(pcBuf); struct ParsedRequest *req = ParsedRequest_create(); if(ParsedRequest_parse(req, pcBuf, len) <0) { printf("parse failed\n"); return -1; } char *h = req->host; char *p = req->path; get(h, p, cfd); close(cfd); }/* end infinite loop */ /* Clean up */ close(sockfd); return 0; } /* end main */
int main(int argc, char *argv[]) { uint8_t active = 1; int error; int pipefd[2]; /* buffer length in samples. would be multiplied by channels and sample size */ int buffer_length = 1024; int listen_port = 5002; uint32_t counter = 0; pthread_t audio_thr; /* pthread_attr_t audio_thr_attr; */ /* record parameters */ pa_sample_spec ss = { /* for fft need PA_SAMPLE_FLOAT32LE or PA_SAMPLE_FLOAT32BE */ .format = PA_SAMPLE_FLOAT32LE, // PA_SAMPLE_S16LE, .rate = 44100, .channels = 2 }; SAUDIORECTHRPARAMS audio_thr_params = {0}; HPINLIST connection = NULL; HPIN pin, pipe_pin; HBUF sample, dummy_sample; TIMING_MEASURE_AREA; if (argc < 2) { printf("usage: source <listen_port>\n"); } sscanf(argv[1], "%i", &listen_port); printf("Will listen %i port\n", listen_port); connection = pin_list_create(MAX_EVENTS); pin_listen(connection, listen_port, BACKLOG, NULL); dummy_sample = buf_alloc(dummy_size_callback); if (pipe(pipefd) == -1) { handle_error("pipe()"); } setnonblocking(pipefd[0]); setnonblocking(pipefd[1]); pipe_pin = pin_list_add_custom_fd(connection, pipefd[0], PIN_TYPE_CUSTOM); /* thread creation */ audio_thr_params.pipefd = pipefd[1]; audio_thr_params.buffer_size = buffer_length; audio_thr_params.sample_spec = &ss; audio_thr_params.argc = argc; audio_thr_params.argv = argv; audio_thr_params.active = 1; #if 0 if ( (error = pthread_attr_init(&audio_thr_attr)) != 0 ) handle_error_en(error, "pthread_attr_init()"); if ( (error = pthread_attr_setstacksize(&audio_thr_attr, 5000)) != 0) handle_error_en(error, "pthread_attr_setstacksize()"); #endif if ( (error = pthread_create(&audio_thr, NULL, audio_capture_thr, &audio_thr_params)) != 0 ) handle_error_en(error, "pthread_create()"); /** * :TODO: It's need to improve latency while sending buffers */ while (active && pin_list_wait(connection, -1) != PIN_ERROR) { pin_list_deliver(connection); while ( (pin = pin_list_get_next_event(connection, PIN_EVENT_READ)) != NULL ) { if (pin == pipe_pin) { TIMING_START(); counter = 0; while ( pin_read_raw(pin, &sample, PTR_SIZE) != 0 ) { /* if pin = pipe_pin, read pointer to buffer, write buffer into socket and free it */ /* printf("[source] read %p\n", sample); */ print_header((PSSAMPLEHEADER)sample->buf, sample->buf + HEADER_SIZE, sample->size - HEADER_SIZE); pin_list_write_sample(connection, sample, 0); buf_free(sample); counter++; } /* printf("[source] %u samples\n", counter); */ TIMING_END("source"); continue; } switch (pin_read_sample(pin, dummy_sample)) { case PIN_STATUS_READY: { break; } case PIN_STATUS_CLOSED: { if (pin->type == PIN_TYPE_INPUT) { printf("one of inputs closed. exit.\n"); active = 0; continue; } else { printf("connection closed\n"); } pin_disconnect(pin); /* close data and skip iteration */ continue; } case PIN_STATUS_PARTIAL: { printf(" partial data. %u / %u\n", dummy_sample->size, dummy_sample->full_size); /* do nothing since no data ready */ break; } case PIN_STATUS_NO_DATA: { printf(" no data. %u / %u\n", dummy_sample->size, dummy_sample->full_size); /* do nothing since no data ready */ break; } default: { break; } } dummy_sample->size = 0; } } //finish: /* loop until pipe_pin is null. and free recieved buffers. */ audio_thr_params.active = 0; pthread_join(audio_thr, NULL); pin_list_destroy(connection); exit(EXIT_SUCCESS); }
TInt Cstif_3::stif_dbus_connection_pop_message0( CStifItemParser& aItem ) { TestModuleIf().SetBehavior( CTestModuleIf::ETestLeaksRequests ); TestModuleIf().SetBehavior( CTestModuleIf::ETestLeaksHandles ); DBusConnection* connection; DBusError error; DBusMessage* msg; DBusMessage*pop_message; DBusMessage* reply = NULL; char error_name[40]; char error_msg[40]; dbus_int32_t no = 5; dbus_error_init(&error); connection = dbus_bus_get_private(DBUS_BUS_SESSION, &error); if(!connection) { sprintf(error_name, "Error_name : %s", error.name); iLog->Log(_L8(error_name)); sprintf(error_msg, "Error_msg : %s", error.message); iLog->Log(_L8(error_msg)); return 1; } msg = dbus_message_new_method_call("Test.Method.Call1", "/Test/Method/Object", "test.Method.Call", "dbus_connection_pop_message0"); if(msg == NULL) { iLog->Log(_L8("message error")); return 1; } reply = dbus_connection_send_with_reply_and_block(connection, msg, 10000, &error); if(!reply) return handle_error(&error); dbus_message_get_args(reply, &error, DBUS_TYPE_INT32, &no, DBUS_TYPE_INVALID); pop_message = dbus_connection_pop_message (connection ) ; iLog->Log(_L8("Pop message is been executed succesfully")); iLog->Log(_L8("Checking for the message in the Queue")); pop_message = dbus_connection_borrow_message (connection ); if(pop_message == NULL) { iLog->Log(_L8("Queue is empty as the pop message is removed the message from the Queue")); iLog->Log( KSuccess ); dbus_message_unref(msg); dbus_connection_close(connection); dbus_connection_unref(connection); dbus_shutdown(); return KErrNone; } else { iLog->Log(_L8("TEST CASE FAILED")); return 1; } }
static void * audio_capture_thr(void *args) { int error; PSAUDIORECTHRPARAMS params = (PSAUDIORECTHRPARAMS)args; pa_simple *pa_context = NULL; uint8_t active = 1; uint32_t buffer_size; SSAMPLEHEADER sample_header = {0}; HBUF sample; TIMING_MEASURE_AREA; buffer_size = HEADER_SIZE + params->sample_spec->channels * params->buffer_size * pa_sample_size(params->sample_spec); sample_header.number = 0; sample_header.buf_type = BUF_TYPE_INTERLEAVED; sample_header.sample_size = pa_sample_size(params->sample_spec); sample_header.samples = params->buffer_size; sample_header.channels = params->sample_spec->channels; sample_header.samplerate = params->sample_spec->rate; if ( !(pa_context = pa_simple_new(NULL, params->argv[0], PA_STREAM_RECORD, NULL, "record", params->sample_spec, NULL, NULL, &error)) ) { fprintf(stderr, __FILE__": pa_simple_new() failed: %s\n", pa_strerror(error)); goto audio_thr_finish; } printf("[source] audio thr\n"); while (active) { TIMING_START(); sample = buf_alloc(NULL); buf_resize(sample, buffer_size); sample->full_size = sample->size = sample->alloced_size; sample_zero_buffer(sample); memcpy(sample->buf, &sample_header, sizeof(SSAMPLEHEADER)); if (pa_simple_read(pa_context, sample->buf + HEADER_SIZE, sample->alloced_size - HEADER_SIZE, &error) < 0) { fprintf(stderr, __FILE__": pa_simple_read() failed: %s\n", pa_strerror(error)); goto audio_thr_finish; } pa_gettimeofday(&(sample_header.timestamp)); sample_header.number += 1; /* printf("[audio] read %p\n", sample); */ if ( (error = write(params->pipefd, &sample, sizeof(sample))) != sizeof(sample)) { if (error == -1) { handle_error("[audio] write()"); } buf_free(sample); perror("[audio] "); printf("[audio] uverrun. free buffer\n"); } active = params->active; TIMING_END(" audio"); } audio_thr_finish: pa_simple_free(pa_context); return NULL; }
void tcp_data_handler::on_read(int fd) { do { int recv_len = recv(fd,m_rbuf.space(),m_rbuf.space_size(),0) ; if(recv_len >0) { m_rbuf.push_data(recv_len) ; while(m_rbuf.data_size() > 0) { packet_info pi = {0} ; int ret = 0 ; if((ret=get_packet_info(m_rbuf.data(),m_rbuf.data_size(),&pi))!=0) { handle_error(ret); return ; } if( pi.size < 1 || pi.size > 4194304 ) { handle_error(ERROR_TYPE_REQUEST) ; return ; } if(m_rbuf.data_size() >= pi.size ) { if((ret=process_packet(&pi)) !=0 ) { handle_error(ret) ; return ; } m_rbuf.pop_data(pi.size) ; } else { if(m_rbuf.space_size() < pi.size - m_rbuf.data_size()) { if(m_rbuf.resize(m_rbuf.capacity() + pi.size )!=0) { handle_error(ERROR_TYPE_MEMORY) ; return ; } } break ; } } m_rbuf.adjust() ; } else if(recv_len == 0) { //peer close handle_error(ERROR_TYPE_PEER_CLOSE) ; return ; } else { if (errno != EAGAIN && errno != EINTR) { handle_error(ERROR_TYPE_SYSTEM) ; return ; } break ; } }while(m_options & OPTION_READALL) ; }
int main(int argc, char *argv[]) { int wtime, numcpu, opt, s, i; int minload, maxload, loadinc; pthread_attr_t attr; pthread_t *tid; void *res; numcpu = 1; while ((opt = getopt(argc, argv, "t:n:")) != -1) { switch (opt) { case 't': duration = atoi(optarg); break; case 'n': numcpu = atoi(optarg); break; default: /* '?' */ usage(); exit(EXIT_FAILURE); } } loadinc = 1; switch (argc - optind) { case 0: minload = 100; maxload = 100; break; case 1: minload = atoi(argv[optind]); maxload = minload; break; case 3: minload = atoi(argv[optind]); maxload = atoi(argv[optind + 1]); loadinc = atoi(argv[optind + 2]); break; default: /* '?' */ usage(); exit(EXIT_FAILURE); } if (minload < 1 || maxload < 1 || minload > 100 || maxload > 100) { usage(); exit(EXIT_FAILURE); } wtime = getWorkerTime(); duration *= 1000000; for (load = minload; load <= maxload; load += loadinc) { sleeptime = wtime * 100 / load - wtime; printf("Starting %d sec run with\n", duration / 1000000); printf("Load: %d\n", load); printf("Worker time: %d\n", wtime); printf("Sleep time: %d\n", sleeptime); printf("Nr. of CPUs to run on: %d\n", numcpu); s = pthread_attr_init(&attr); if (s != 0) handle_error_en(s, "pthread_attr_init"); tid = malloc(sizeof(pthread_t) * numcpu); if (tid == NULL) handle_error("malloc"); for (i = 0; i<numcpu; i++) { s = pthread_create(&tid[i], &attr, &runWorker, NULL); if (s != 0) handle_error_en(s, "pthread_create"); } s = pthread_attr_destroy(&attr); if (s != 0) handle_error_en(s, "pthread_attr_destroy"); for (i = 0; i < numcpu; i++) { s = pthread_join(tid[i], &res); if (s != 0) handle_error_en(s, "pthread_join"); } free(tid); } exit(EXIT_SUCCESS); }
int main (int argc, char **argv) { int ret; int ii, i, inp; char buffer[MAX_BUF + 1]; char *session_data = NULL; char *session_id = NULL; size_t session_data_size; size_t session_id_size = 0; int user_term = 0, retval = 0; socket_st hd; ssize_t bytes; set_program_name (argv[0]); gaa_parser (argc, argv); gnutls_global_set_log_function (tls_log_func); gnutls_global_set_log_level (info.debug); if ((ret = gnutls_global_init ()) < 0) { fprintf (stderr, "global_init: %s\n", gnutls_strerror (ret)); exit (1); } #ifdef ENABLE_PKCS11 pkcs11_common (); #endif if (hostname == NULL) { fprintf (stderr, "No hostname given\n"); exit (1); } sockets_init (); #ifndef _WIN32 signal (SIGPIPE, SIG_IGN); #endif init_global_tls_stuff (); socket_open (&hd, hostname, service); socket_connect (&hd); hd.session = init_tls_session (hostname); if (starttls) goto after_handshake; for (i = 0; i < 2; i++) { if (i == 1) { hd.session = init_tls_session (hostname); gnutls_session_set_data (hd.session, session_data, session_data_size); free (session_data); } ret = do_handshake (&hd); if (ret < 0) { fprintf (stderr, "*** Handshake has failed\n"); gnutls_perror (ret); gnutls_deinit (hd.session); return 1; } else { printf ("- Handshake was completed\n"); if (gnutls_session_is_resumed (hd.session) != 0) printf ("*** This is a resumed session\n"); } if (resume != 0 && i == 0) { gnutls_session_get_data (hd.session, NULL, &session_data_size); session_data = malloc (session_data_size); gnutls_session_get_data (hd.session, session_data, &session_data_size); gnutls_session_get_id (hd.session, NULL, &session_id_size); session_id = malloc (session_id_size); gnutls_session_get_id (hd.session, session_id, &session_id_size); /* print some information */ print_info (hd.session, hostname, info.insecure); printf ("- Disconnecting\n"); socket_bye (&hd); printf ("\n\n- Connecting again- trying to resume previous session\n"); socket_open (&hd, hostname, service); socket_connect (&hd); } else { break; } } after_handshake: /* Warning! Do not touch this text string, it is used by external programs to search for when gnutls-cli has reached this point. */ printf ("\n- Simple Client Mode:\n\n"); if (rehandshake) { ret = do_handshake (&hd); if (ret < 0) { fprintf (stderr, "*** ReHandshake has failed\n"); gnutls_perror (ret); gnutls_deinit (hd.session); return 1; } else { printf ("- ReHandshake was completed\n"); } } #ifndef _WIN32 signal (SIGALRM, &starttls_alarm); #endif fflush (stdout); fflush (stderr); /* do not buffer */ #if !(defined _WIN32 || defined __WIN32__) setbuf (stdin, NULL); #endif setbuf (stdout, NULL); setbuf (stderr, NULL); for (;;) { if (starttls_alarmed && !hd.secure) { /* Warning! Do not touch this text string, it is used by external programs to search for when gnutls-cli has reached this point. */ fprintf (stderr, "*** Starting TLS handshake\n"); ret = do_handshake (&hd); if (ret < 0) { fprintf (stderr, "*** Handshake has failed\n"); user_term = 1; retval = 1; break; } } inp = check_net_or_keyboard_input(&hd); if (inp == IN_NET) { memset (buffer, 0, MAX_BUF + 1); ret = socket_recv (&hd, buffer, MAX_BUF); if (ret == 0) { printf ("- Peer has closed the GnuTLS connection\n"); break; } else if (handle_error (&hd, ret) < 0 && user_term == 0) { fprintf (stderr, "*** Server has terminated the connection abnormally.\n"); retval = 1; break; } else if (ret > 0) { if (verbose != 0) printf ("- Received[%d]: ", ret); for (ii = 0; ii < ret; ii++) { fputc (buffer[ii], stdout); } fflush (stdout); } if (user_term != 0) break; } if (inp == IN_KEYBOARD) { if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0) { if (hd.secure == 0) { /* Warning! Do not touch this text string, it is used by external programs to search for when gnutls-cli has reached this point. */ fprintf (stderr, "*** Starting TLS handshake\n"); ret = do_handshake (&hd); clearerr (stdin); if (ret < 0) { fprintf (stderr, "*** Handshake has failed\n"); user_term = 1; retval = 1; break; } } else { user_term = 1; break; } continue; } buffer[bytes] = 0; if (crlf != 0) { char *b = strchr (buffer, '\n'); if (b != NULL) { strcpy (b, "\r\n"); bytes++; } } ret = socket_send (&hd, buffer, bytes); if (ret > 0) { if (verbose != 0) printf ("- Sent: %d bytes\n", ret); } else handle_error (&hd, ret); } } if (user_term != 0) socket_bye (&hd); else gnutls_deinit (hd.session); #ifdef ENABLE_SRP if (srp_cred) gnutls_srp_free_client_credentials (srp_cred); #endif #ifdef ENABLE_PSK if (psk_cred) gnutls_psk_free_client_credentials (psk_cred); #endif gnutls_certificate_free_credentials (xcred); #ifdef ENABLE_ANON gnutls_anon_free_client_credentials (anon_cred); #endif gnutls_global_deinit (); return retval; }
int main(int argc, char **argv) { int *buf, i, rank, nprocs, len, sum; int global_sum; int errs=0, toterrs, errcode; char *filename; MPI_File fh; MPI_Status status; MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); double wr_stime, wr_etime, wr_time, wr_sumtime; double rd_stime, rd_etime, rd_time, rd_sumtime; /* process 0 takes the file name as a command-line argument and broadcasts it to other processes */ if (!rank) { i = 1; while ((i < argc) && strcmp("-fname", *argv)) { i++; argv++; } if (i >= argc) { fprintf(stderr, "\n*# Usage: shared_fp -fname filename\n\n"); MPI_Abort(MPI_COMM_WORLD, 1); } argv++; len = strlen(*argv); filename = (char *) malloc(len+10); strcpy(filename, *argv); MPI_Bcast(&len, 1, MPI_INT, 0, MPI_COMM_WORLD); MPI_Bcast(filename, len+10, MPI_CHAR, 0, MPI_COMM_WORLD); } else { MPI_Bcast(&len, 1, MPI_INT, 0, MPI_COMM_WORLD); filename = (char *) malloc(len+10); MPI_Bcast(filename, len+10, MPI_CHAR, 0, MPI_COMM_WORLD); } buf = (int *) malloc(COUNT * sizeof(int)); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); for (i=0; i<COUNT; i++) buf[i] = COUNT*rank + i; errcode = MPI_File_open(MPI_COMM_WORLD, filename, MPI_MODE_CREATE | MPI_MODE_RDWR, MPI_INFO_NULL, &fh); if (errcode != MPI_SUCCESS) { handle_error(errcode, "MPI_File_open"); } wr_stime = MPI_Wtime(); errcode = MPI_File_write_ordered(fh, buf, COUNT, MPI_INT, &status); if (errcode != MPI_SUCCESS) { handle_error(errcode, "MPI_File_write_shared"); } wr_etime = MPI_Wtime(); for (i=0; i<COUNT; i++) buf[i] = 0; MPI_Barrier(MPI_COMM_WORLD); rd_stime = MPI_Wtime(); errcode = MPI_File_seek_shared(fh, 0, MPI_SEEK_SET); if (errcode != MPI_SUCCESS) { handle_error(errcode, "MPI_File_seek_shared"); } errcode = MPI_File_read_ordered(fh, buf, COUNT, MPI_INT, &status); if (errcode != MPI_SUCCESS) { handle_error(errcode, "MPI_File_read_shared"); } rd_etime = MPI_Wtime(); MPI_File_close(&fh); sum = 0; for (i=0; i<COUNT; i++) sum += buf[i]; MPI_Allreduce(&sum, &global_sum, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); wr_time = wr_etime - wr_stime; rd_time = rd_etime - rd_stime; MPI_Allreduce(&wr_time, &wr_sumtime, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(&rd_time, &rd_sumtime, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); if (global_sum != (((COUNT*nprocs - 1)*(COUNT*nprocs))/2)) { errs++; fprintf(stderr, "Error: sum %d, global_sum %d, %d\n", sum, global_sum,(((COUNT*nprocs - 1)*(COUNT*nprocs))/2)); } free(buf); free(filename); MPI_Allreduce( &errs, &toterrs, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD ); if (rank == 0) { if( toterrs > 0) { fprintf( stderr, "Found %d errors\n", toterrs ); } else { fprintf( stdout, " No Errors\n" ); #ifdef TIMING fprintf( stderr, "nprocs: %d bytes: %d write: %f read %f\n", nprocs, COUNT*sizeof(int), wr_sumtime, rd_sumtime); #endif } } MPI_Finalize(); return 0; }