void launch_server() { int s = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in a; memset(&a, 0, sizeof(struct sockaddr_in)); a.sin_family = AF_INET; a.sin_port = 0; if((a.sin_addr.s_addr = getPublicIPAddr()) == 0) { fprintf(stderr, "Could not get public ip address. Exiting...\n"); exit(0); } if(mybind(s, &a) < 0) { fprintf(stderr, "mybind() failed. Exiting...\n"); exit(0); } printf("%s %u\n", inet_ntoa(a.sin_addr), ntohs(a.sin_port)); if(listen(s, 0) < 0) { perror("listen"); exit(0); } memset(&a, 0, sizeof(struct sockaddr_in)); socklen_t alen = sizeof(struct sockaddr_in); int asock = -1; while((asock = accept(s, (struct sockaddr *)&a, &alen)) > 0) { /* Single-threaded */ char *fname; int nparams; arg_type *a = NULL; return_type ret; recvCall(asock, &fname, &nparams, &a); #ifdef _DEBUG_1_ printf("launch_server(), before makeCall()\n"); fflush(stdout); #endif makeCall(fname, nparams, a, &ret); #ifdef _DEBUG_1_ printf("launch_server(), after makeCall()\n"); fflush(stdout); #endif returnResult(asock, &ret); free(fname); freeArgs(a); freeRet(ret); shutdown(asock, SHUT_RDWR); close(asock); asock = -1; } /* WARNING -- massive memory, linked list of registered * functions! We assume that the process exits at this * point, and so do not bother freeing the memory. */ return; }
/** * The main macro recursion loop. * @todo Dynamically reallocate target buffer. * @param mb macro expansion state * @return 0 on success, 1 on failure */ static int expandMacro(MacroBuf mb) { rpmMacroEntry *mep; rpmMacroEntry me; const char *s = mb->s, *se; const char *f, *fe; const char *g, *ge; size_t fn, gn; char *t = mb->t; /* save expansion pointer for printExpand */ int c; int rc = 0; int negate; const char * lastc; int chkexist; if (++mb->depth > max_macro_depth) { rpmlog(RPMLOG_ERR, _("Recursion depth(%d) greater than max(%d)\n"), mb->depth, max_macro_depth); mb->depth--; mb->expand_trace = 1; return 1; } while (rc == 0 && mb->nb > 0 && (c = *s) != '\0') { s++; /* Copy text until next macro */ switch(c) { case '%': if (*s) { /* Ensure not end-of-string. */ if (*s != '%') break; s++; /* skip first % in %% */ } default: SAVECHAR(mb, c); continue; break; } /* Expand next macro */ f = fe = NULL; g = ge = NULL; if (mb->depth > 1) /* XXX full expansion for outermost level */ t = mb->t; /* save expansion pointer for printExpand */ negate = 0; lastc = NULL; chkexist = 0; switch ((c = *s)) { default: /* %name substitution */ while (strchr("!?", *s) != NULL) { switch(*s++) { case '!': negate = ((negate + 1) % 2); break; case '?': chkexist++; break; } } f = se = s; if (*se == '-') se++; while((c = *se) && (risalnum(c) || c == '_')) se++; /* Recognize non-alnum macros too */ switch (*se) { case '*': se++; if (*se == '*') se++; break; case '#': se++; break; default: break; } fe = se; /* For "%name " macros ... */ if ((c = *fe) && isblank(c)) if ((lastc = strchr(fe,'\n')) == NULL) lastc = strchr(fe, '\0'); break; case '(': /* %(...) shell escape */ if ((se = matchchar(s, c, ')')) == NULL) { rpmlog(RPMLOG_ERR, _("Unterminated %c: %s\n"), (char)c, s); rc = 1; continue; } if (mb->macro_trace) printMacro(mb, s, se+1); s++; /* skip ( */ rc = doShellEscape(mb, s, (se - s)); se++; /* skip ) */ s = se; continue; break; case '{': /* %{...}/%{...:...} substitution */ if ((se = matchchar(s, c, '}')) == NULL) { rpmlog(RPMLOG_ERR, _("Unterminated %c: %s\n"), (char)c, s); rc = 1; continue; } f = s+1;/* skip { */ se++; /* skip } */ while (strchr("!?", *f) != NULL) { switch(*f++) { case '!': negate = ((negate + 1) % 2); break; case '?': chkexist++; break; } } for (fe = f; (c = *fe) && !strchr(" :}", c);) fe++; switch (c) { case ':': g = fe + 1; ge = se - 1; break; case ' ': lastc = se-1; break; default: break; } break; } /* XXX Everything below expects fe > f */ fn = (fe - f); gn = (ge - g); if ((fe - f) <= 0) { /* XXX Process % in unknown context */ c = '%'; /* XXX only need to save % */ SAVECHAR(mb, c); #if 0 rpmlog(RPMLOG_ERR, _("A %% is followed by an unparseable macro\n")); #endif s = se; continue; } if (mb->macro_trace) printMacro(mb, s, se); /* Expand builtin macros */ if (STREQ("global", f, fn)) { s = doDefine(mb, se, RMIL_GLOBAL, 1); continue; } if (STREQ("define", f, fn)) { s = doDefine(mb, se, mb->depth, 0); continue; } if (STREQ("undefine", f, fn)) { s = doUndefine(mb->mc, se); continue; } if (STREQ("echo", f, fn) || STREQ("warn", f, fn) || STREQ("error", f, fn)) { int waserror = 0; if (STREQ("error", f, fn)) waserror = 1; if (g != NULL && g < ge) doOutput(mb, waserror, g, gn); else doOutput(mb, waserror, f, fn); s = se; continue; } if (STREQ("trace", f, fn)) { /* XXX TODO restore expand_trace/macro_trace to 0 on return */ mb->expand_trace = mb->macro_trace = (negate ? 0 : mb->depth); if (mb->depth == 1) { print_macro_trace = mb->macro_trace; print_expand_trace = mb->expand_trace; } s = se; continue; } if (STREQ("dump", f, fn)) { rpmDumpMacroTable(mb->mc, NULL); while (iseol(*se)) se++; s = se; continue; } #ifdef WITH_LUA if (STREQ("lua", f, fn)) { rpmlua lua = NULL; /* Global state. */ const char *ls = s+sizeof("{lua:")-1; const char *lse = se-sizeof("}")+1; char *scriptbuf = (char *)xmalloc((lse-ls)+1); const char *printbuf; memcpy(scriptbuf, ls, lse-ls); scriptbuf[lse-ls] = '\0'; rpmluaSetPrintBuffer(lua, 1); if (rpmluaRunScript(lua, scriptbuf, NULL) == -1) rc = 1; printbuf = rpmluaGetPrintBuffer(lua); if (printbuf) { size_t len = strlen(printbuf); if (len > mb->nb) len = mb->nb; memcpy(mb->t, printbuf, len); mb->t += len; mb->nb -= len; } rpmluaSetPrintBuffer(lua, 0); free(scriptbuf); s = se; continue; } #endif /* XXX necessary but clunky */ if (STREQ("basename", f, fn) || STREQ("suffix", f, fn) || STREQ("expand", f, fn) || STREQ("verbose", f, fn) || STREQ("uncompress", f, fn) || STREQ("url2path", f, fn) || STREQ("u2p", f, fn) || STREQ("getenv", f, fn) || STREQ("S", f, fn) || STREQ("P", f, fn) || STREQ("F", f, fn)) { /* FIX: verbose may be set */ doFoo(mb, negate, f, fn, g, gn); s = se; continue; } /* Expand defined macros */ mep = findEntry(mb->mc, f, fn); me = (mep ? *mep : NULL); /* XXX Special processing for flags */ if (*f == '-') { if (me) me->used++; /* Mark macro as used */ if ((me == NULL && !negate) || /* Without -f, skip %{-f...} */ (me != NULL && negate)) { /* With -f, skip %{!-f...} */ s = se; continue; } if (g && g < ge) { /* Expand X in %{-f:X} */ rc = expandT(mb, g, gn); } else if (me && me->body && *me->body) {/* Expand %{-f}/%{-f*} */ rc = expandT(mb, me->body, strlen(me->body)); } s = se; continue; } /* XXX Special processing for macro existence */ if (chkexist) { if ((me == NULL && !negate) || /* Without -f, skip %{?f...} */ (me != NULL && negate)) { /* With -f, skip %{!?f...} */ s = se; continue; } if (g && g < ge) { /* Expand X in %{?f:X} */ rc = expandT(mb, g, gn); } else if (me && me->body && *me->body) { /* Expand %{?f}/%{?f*} */ rc = expandT(mb, me->body, strlen(me->body)); } s = se; continue; } if (me == NULL) { /* leave unknown %... as is */ #ifndef HACK #if DEAD /* XXX hack to skip over empty arg list */ if (fn == 1 && *f == '*') { s = se; continue; } #endif /* XXX hack to permit non-overloaded %foo to be passed */ c = '%'; /* XXX only need to save % */ SAVECHAR(mb, c); #else rpmlog(RPMLOG_ERR, _("Macro %%%.*s not found, skipping\n"), fn, f); s = se; #endif continue; } /* Setup args for "%name " macros with opts */ if (me && me->opts != NULL) { if (lastc != NULL) { se = grabArgs(mb, me, fe, lastc); } else { addMacro(mb->mc, "**", NULL, "", mb->depth); addMacro(mb->mc, "*", NULL, "", mb->depth); addMacro(mb->mc, "#", NULL, "0", mb->depth); addMacro(mb->mc, "0", NULL, me->name, mb->depth); } } /* Recursively expand body of macro */ if (me->body && *me->body) { mb->s = me->body; rc = expandMacro(mb); if (rc == 0) me->used++; /* Mark macro as used */ } /* Free args for "%name " macros with opts */ if (me->opts != NULL) freeArgs(mb); s = se; } *mb->t = '\0'; mb->s = s; mb->depth--; if (rc != 0 || mb->expand_trace) printExpansion(mb, t, mb->t); return rc; }
int main(int argc, char* argv[]) { // Parse command line arguments, use defaults when needed ArgumentStruct* args; args = parseArguments(argc, argv); // Struct to store response from CURL MessageStruct response; struct tm* lastUpdated = getTime(&response, args->url); // Preapre response for re-use freeResponse(response); // Get RSS feed from server if (args->update) { // If we're either not refetching the same URL, or it has updates if (args->ignoreTimestamp || fetchingNewURL(args) || args->previouslyFetchedURL == NULL || timeDiff(&(args->lastUpdated), lastUpdated)) { if(get(&response, args->url)) { printf("ERROR : Could not find feed at %s\n", args->url); freeArgs(args); return 1; } // Write result out to file if(storeFeed(response, args->dataFile, args->tempDirectory)) { printf("ERROR : Writing response to file (Running again should fix this)\n"); freeArgs(args); return 1; } } else { printf("No updates for feed : %s\n", args->url); freeArgs(args); return 0; } } // Create array of article sturctures RSSFeed* feed = NULL; feed = parseFeed(args); // Display feed displayFeed(feed, args); storeSettings(args, feed); // Free everything that has been dynamically allocated freeFeed(feed); freeResponse(response); freeArgs(args); return 0; }
/// \details Initialize a Command structure with default values, then /// parse any command line arguments that were supplied to overwrite /// defaults. /// /// \param [in] argc the number of command line arguments /// \param [in] argv the command line arguments array Command parseCommandLine(int argc, char** argv) { Command cmd; memset(cmd.potDir, 0, 1024); memset(cmd.potName, 0, 1024); memset(cmd.potType, 0, 1024); strcpy(cmd.potDir, "pots"); strcpy(cmd.potName, "\0"); // default depends on potType strcpy(cmd.potType, "funcfl"); cmd.doeam = 0; cmd.nx = 20; cmd.ny = 20; cmd.nz = 20; cmd.xproc = 1; cmd.yproc = 1; cmd.zproc = 1; cmd.nSteps = 100; cmd.printRate = 10; cmd.dt = 1.0; cmd.lat = -1.0; cmd.temperature = 600.0; cmd.initialDelta = 0.0; cmd.relativeSkinDistance= 0.1; cmd.doHilbert = 0; // gpu-specific memset(cmd.method, 0, 1024); strcpy(cmd.method, "thread_atom"); cmd.gpuAsync = 0; cmd.gpuProfile = 0; cmd.ljInterpolation = 0; cmd.spline = 0; int help=0; // add arguments for processing. Please update the html documentation too! addArg("help", 'h', 0, 'i', &(help), 0, "print this message"); addArg("potDir", 'd', 1, 's', cmd.potDir, sizeof(cmd.potDir), "potential directory"); addArg("potName", 'p', 1, 's', cmd.potName, sizeof(cmd.potName), "potential name"); addArg("potType", 't', 1, 's', cmd.potType, sizeof(cmd.potType), "potential type (funcfl or setfl)"); addArg("doeam", 'e', 0, 'i', &(cmd.doeam), 0, "compute eam potentials"); addArg("nx", 'x', 1, 'i', &(cmd.nx), 0, "number of unit cells in x"); addArg("ny", 'y', 1, 'i', &(cmd.ny), 0, "number of unit cells in y"); addArg("nz", 'z', 1, 'i', &(cmd.nz), 0, "number of unit cells in z"); addArg("xproc", 'i', 1, 'i', &(cmd.xproc), 0, "processors in x direction"); addArg("yproc", 'j', 1, 'i', &(cmd.yproc), 0, "processors in y direction"); addArg("zproc", 'k', 1, 'i', &(cmd.zproc), 0, "processors in z direction"); addArg("nSteps", 'N', 1, 'i', &(cmd.nSteps), 0, "number of time steps"); addArg("printRate", 'n', 1, 'i', &(cmd.printRate), 0, "number of steps between output"); addArg("dt", 'D', 1, 'd', &(cmd.dt), 0, "time step (in fs)"); addArg("lat", 'l', 1, 'd', &(cmd.lat), 0, "lattice parameter (Angstroms)"); addArg("temp", 'T', 1, 'd', &(cmd.temperature), 0, "initial temperature (K)"); addArg("delta", 'r', 1, 'd', &(cmd.initialDelta), 0, "initial delta (Angstroms)"); addArg("hilbert", 'H', 0, 'd', &(cmd.doHilbert), 0, "space-filling curve for the traversal of cells"); addArg("skinDistance",'S', 1, 'd', &(cmd.relativeSkinDistance), 0, "skinDistance (relative to cutoff (default: 0.1))"); addArg("method", 'm', 1, 's', cmd.method, sizeof(cmd.method), "thread_atom,warp_atom,warp_atom_nl,cta_cell,thread_atom_nl,cpu_nl"); // gpu-specific addArg("gpuAsync", 'a', 1, 'i', &(cmd.gpuAsync), 0, "communicaton hiding optimization using streams"); addArg("gpuProfile", 's', 0, 'i', &(cmd.gpuProfile), 0, "profiling mode: reboxing disabled, single kernel run"); addArg("ljInterpolation", 'I', 0, 'i', &(cmd.ljInterpolation), 0, "compute Lennard-Jones potential using interpolation (gpu only)"); addArg("spline", 'P', 0, 'i', &(cmd.spline), 0, "use splines for interpolation (gpu only)"); addArg("usePairlist", 'L', 0, 'i', &(cmd.usePairlist), 0, "use pairlists for cta_cell method in Lennard-Jones computation"); processArgs(argc,argv); // If user didn't set potName, set type dependent default. if (strlen(cmd.potName) == 0) { if (strcmp(cmd.potType, "setfl" ) == 0) strcpy(cmd.potName, "Cu01.eam.alloy"); if (strcmp(cmd.potType, "funcfl") == 0) strcpy(cmd.potName, "Cu_u6.eam"); } if (help) { printArgs(); freeArgs(); exit(2); } freeArgs(); return cmd; }
JNIEXPORT jobject JNICALL Java_gnu_rrd_RRDJNI_info (JNIEnv *env, jclass cl, jobjectArray argv) { char **argv2; rrd_info_t *info, *save; jclass HashtableClass; jmethodID HashtableMethodInit; jmethodID HashtableMethodPut; jclass RRDInfoClass; jmethodID RRDInfoMethodVal; jmethodID RRDInfoMethodCnt; jmethodID RRDInfoMethodStr; jmethodID RRDInfoMethodDate; jclass DateClass; jmethodID DateMethodInit; jobject DateObj; jobject rtnObj; jstring key; jdouble value; jlong counter; jstring strval; HashtableClass = (*env)->FindClass(env, "java/util/Hashtable"); HashtableMethodInit = (*env)->GetMethodID(env, HashtableClass, "<init>", "()V"); HashtableMethodPut = (*env)->GetMethodID(env, HashtableClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); RRDInfoClass = (*env)->FindClass(env, "gnu/rrd/RRDInfo"); RRDInfoMethodVal = (*env)->GetMethodID(env, RRDInfoClass, "<init>", "(D)V"); RRDInfoMethodCnt = (*env)->GetMethodID(env, RRDInfoClass, "<init>", "(J)V"); RRDInfoMethodStr = (*env)->GetMethodID(env, RRDInfoClass, "<init>", "(Ljava/lang/String;)V"); RRDInfoMethodDate = (*env)->GetMethodID(env, RRDInfoClass, "<init>", "(Ljava/util/Date;)V"); DateClass = (*env)->FindClass(env, "java/util/Date"); DateMethodInit = (*env)->GetMethodID(env, DateClass, "<init>", "(J)V"); rtnObj = (*env)->NewObject(env, HashtableClass, HashtableMethodInit, NULL); argv2 = initArgs(env, argv, "last"); info = rrd_info((*env)->GetArrayLength(env, argv)+1, argv2); while (info) { save=info; key = (jstring)(*env)->NewStringUTF(env, info->key); switch (info->type) { case RD_I_VAL: value = info->value.u_val; (*env)->CallVoidMethod(env, rtnObj, HashtableMethodPut, key, (*env)->NewObject(env, RRDInfoClass, RRDInfoMethodVal, value), NULL); break; case RD_I_CNT: counter = info->value.u_cnt; if (strcmp(info->key, "last_update")==0) { (*env)->CallVoidMethod(env, rtnObj, HashtableMethodPut, key, (*env)->NewObject(env, RRDInfoClass, RRDInfoMethodDate, (*env)->NewObject(env, DateClass, DateMethodInit, counter*1000)), NULL); } else { (*env)->CallVoidMethod(env, rtnObj, HashtableMethodPut, key, (*env)->NewObject(env, RRDInfoClass, RRDInfoMethodCnt, counter), NULL); } break; case RD_I_STR: strval = (jstring)(*env)->NewStringUTF(env, info->value.u_str); (*env)->CallVoidMethod(env, rtnObj, HashtableMethodPut, key, (*env)->NewObject(env, RRDInfoClass, RRDInfoMethodStr, strval), NULL); break; } info = info->next; free(save); } free(info); freeArgs(env, argv, argv2); if (rrd_test_error()) throwException(env, "gnu/rrd/RRDException", rrd_get_error()); return rtnObj; }
JNIEXPORT jobject JNICALL Java_gnu_rrd_RRDJNI_fetch (JNIEnv *env, jclass cl, jobjectArray argv) { time_t start, end; unsigned long step, ds_cnt, i, ii; rrd_value_t *data, *datai; char **ds_namv; char s[30]; char **argv2; jclass VectorClass; jmethodID VectorMethodInit; jmethodID VectorMethodAdd; jclass DateClass; jmethodID DateMethodInit; jclass DoubleClass; jmethodID DoubleMethodInit; jclass RRDRecClass; jmethodID RRDRecMethodInit; jobject dateObj; jdouble dataObj; jobject dsObj; jobject rtnObj; jlong timestamp; VectorClass = (*env)->FindClass(env, "java/util/Vector"); VectorMethodInit = (*env)->GetMethodID(env, VectorClass, "<init>", "()V"); VectorMethodAdd = (*env)->GetMethodID(env, VectorClass, "addElement", "(Ljava/lang/Object;)V"); DateClass = (*env)->FindClass(env, "java/util/Date"); DateMethodInit = (*env)->GetMethodID(env, DateClass, "<init>", "(J)V"); DoubleClass = (*env)->FindClass(env, "java/lang/Double"); DoubleMethodInit = (*env)->GetMethodID(env, DoubleClass, "<init>", "(D)V"); RRDRecClass = (*env)->FindClass(env, "gnu/rrd/RRDRec"); RRDRecMethodInit = (*env)->GetMethodID(env, RRDRecClass, "<init>", "(Ljava/util/Date;Ljava/util/Vector;)V"); rtnObj = (*env)->NewObject(env, VectorClass, VectorMethodInit, NULL); argv2 = initArgs(env, argv, "fetch"); if (rrd_fetch((*env)->GetArrayLength(env, argv)+1, argv2, &start, &end, &step, &ds_cnt, &ds_namv, &data) != -1) { datai = data; for (i = start; i <= end; i += step) { timestamp = i; dateObj = (*env)->NewObject(env, DateClass, DateMethodInit, timestamp*1000); dsObj = (*env)->NewObject(env, VectorClass, VectorMethodInit, NULL); for (ii = 0; ii < ds_cnt; ii++) { dataObj = *(datai++); (*env)->CallVoidMethod(env, dsObj, VectorMethodAdd, (*env)->NewObject(env, DoubleClass, DoubleMethodInit, dataObj)); } (*env)->CallVoidMethod(env, rtnObj, VectorMethodAdd, (*env)->NewObject(env, RRDRecClass, RRDRecMethodInit, dateObj, dsObj)); } for (i=0; i<ds_cnt; i++) free(ds_namv[i]); free(ds_namv); free(data); } freeArgs(env, argv, argv2); if (rrd_test_error()) throwException(env, "gnu/rrd/RRDException", rrd_get_error()); return rtnObj; }
// p2 // given a command and argument (in form args), forks and execs the call to shell. // performs redirects, backgrounding and piping as given. void p2(struct args *arguments){ FILE *input, *output; /*while (NULL != args[len]) len++;*/ child = fork(); if (-1 == child){ perror("Fork failed"); exit(EXIT_FAILURE); } if (child){ int status; if (arguments->background) waitpid(-1, &status, WNOHANG); else { //printf("fg\n"); //signal(SIGINT, sigHandler); waitpid(-1, &status, WCONTINUED); freeArgs(arguments); } } else { int pipebool = 0; if (arguments->in_redir) { input = fopen(arguments->in_file, "r"); dup2(fileno(input), STDIN_FILENO); fclose(input); } if (arguments->out_redir) { output = fopen(arguments->out_file, "w"); dup2(fileno(output), STDOUT_FILENO); fclose(output); } if (NULL != arguments->pipe_args[0] && arguments->pipe_args[0][0] == '|') { char ***b = pipearg(arguments); pipebool = 1; char *s = arguments->pipe_args[0]; int i, numpipe; i = numpipe = 0; while( s != NULL ){ // count number of pipes if(strcmp(s,"|") == 0) numpipe++; i++; s = arguments->pipe_args[i]; } piper(b,numpipe); /*pid_t forkChild; int fd[2]; pipe(fd); forkChild = fork(); if(-1 == forkChild){ perror("Fork failed"); exit(EXIT_FAILURE); } else if(forkChild == 0){ // Before pipe close(fd[0]); dup2(fd[1], STDOUT_FILENO); // Change child's input to tunnel output close(fd[1]); execvp(arguments->program, arguments->program_args); // Executes child's program } else{ // After pipe close(fd[1]); // Close unnecessary parent input link to tunnel dup2(fd[0], STDIN_FILENO); // Change parent's output to tunnel input close(fd[0]); char *cprog = arguments->pipe_args[1]; // Name child's program char **cpargs; // Initialize child's program arguments int i = 0; while(NULL != arguments->pipe_args[i+1]) // Get number of child's program arguments (terminating NULL included) i++; cpargs = malloc(sizeof(char *) * (i + 1)); for (int j = 0; j < i; j++) { // Fill child's program args int len = strlen(arguments->pipe_args[j+1]) + 1; cpargs[j] = malloc(sizeof(char) * len); allocCheck(cpargs[j]); strncpy(cpargs[j], arguments->pipe_args[j+1], len); } cpargs[i] = NULL; execvp(cprog,cpargs); // Executes child's program string_array_free(cpargs); }*/ } if(pipebool == 0) execvp(arguments->program, arguments->program_args); if (errno) { perror("Exec failed"); freeArgs(arguments); //argFree(args); //exit(EXIT_FAILURE); } } }
/// \details Initialize a Command structure with default values, then /// parse any command line arguments that were supplied to overwrite /// defaults. /// /// \param [in] argc the number of command line arguments /// \param [in] argv the command line arguments array Command parseCommandLine(int argc, char** argv) { Command cmd; memset(cmd.potDir, 0, 1024); memset(cmd.potName, 0, 1024); memset(cmd.potType, 0, 1024); strcpy(cmd.potDir, "pots"); strcpy(cmd.potName, "\0"); // default depends on potType strcpy(cmd.potType, "funcfl"); cmd.doeam = 0; cmd.nx = 20; cmd.ny = 20; cmd.nz = 20; cmd.xproc = 1; cmd.yproc = 1; cmd.zproc = 1; cmd.nSteps = 100; cmd.printRate = 10; cmd.dt = 1.0; cmd.lat = -1.0; cmd.temperature = 600.0; cmd.initialDelta = 0.0; int help=0; // add arguments for processing. Please update the html documentation too! addArg("help", 'h', 0, 'i', &(help), 0, "print this message"); addArg("potDir", 'd', 1, 's', cmd.potDir, sizeof(cmd.potDir), "potential directory"); addArg("potName", 'p', 1, 's', cmd.potName, sizeof(cmd.potName), "potential name"); addArg("potType", 't', 1, 's', cmd.potType, sizeof(cmd.potType), "potential type (funcfl or setfl)"); addArg("doeam", 'e', 0, 'i', &(cmd.doeam), 0, "compute eam potentials"); addArg("nx", 'x', 1, 'i', &(cmd.nx), 0, "number of unit cells in x"); addArg("ny", 'y', 1, 'i', &(cmd.ny), 0, "number of unit cells in y"); addArg("nz", 'z', 1, 'i', &(cmd.nz), 0, "number of unit cells in z"); addArg("xproc", 'i', 1, 'i', &(cmd.xproc), 0, "processors in x direction"); addArg("yproc", 'j', 1, 'i', &(cmd.yproc), 0, "processors in y direction"); addArg("zproc", 'k', 1, 'i', &(cmd.zproc), 0, "processors in z direction"); addArg("nSteps", 'N', 1, 'i', &(cmd.nSteps), 0, "number of time steps"); addArg("printRate", 'n', 1, 'i', &(cmd.printRate), 0, "number of steps between output"); addArg("dt", 'D', 1, 'd', &(cmd.dt), 0, "time step (in fs)"); addArg("lat", 'l', 1, 'd', &(cmd.lat), 0, "lattice parameter (Angstroms)"); addArg("temp", 'T', 1, 'd', &(cmd.temperature), 0, "initial temperature (K)"); addArg("delta", 'r', 1, 'd', &(cmd.initialDelta), 0, "initial delta (Angstroms)"); processArgs(argc,argv); // If user didn't set potName, set type dependent default. if (strlen(cmd.potName) == 0) { if (strcmp(cmd.potType, "setfl" ) == 0) strcpy(cmd.potName, "Cu01.eam.alloy"); if (strcmp(cmd.potType, "funcfl") == 0) strcpy(cmd.potName, "Cu_u6.eam"); } if (help) { printArgs(); freeArgs(); exit(2); } freeArgs(); return cmd; }
CmsRet oal_spawnProcess(const SpawnProcessInfo *spawnInfo, SpawnedProcessInfo *procInfo) { char **argv=NULL; SINT32 pid, i; CmsRet ret=CMSRET_SUCCESS; if ((ret = parseArgs(spawnInfo->exe, spawnInfo->args, &argv)) != CMSRET_SUCCESS) { return ret; } pid = fork(); if (pid == 0) { SINT32 devNullFd=-1, fd; /* * This is the child. */ /* * If user gave us specific instructions on fd re-routing, * do it before execv. */ if ((spawnInfo->stdinFd == -1) || (spawnInfo->stdoutFd == -1) || (spawnInfo->stderrFd == -1)) { devNullFd = open("/dev/null", O_RDWR); if (devNullFd == -1) { cmsLog_error("open of /dev/null failed"); exit(-1); } } if (spawnInfo->stdinFd != 0) { close(0); fd = (spawnInfo->stdinFd == -1) ? devNullFd : spawnInfo->stdinFd; dup2(fd, 0); } if (spawnInfo->stdoutFd != 1) { close(1); fd = (spawnInfo->stdoutFd == -1) ? devNullFd : spawnInfo->stdoutFd; dup2(fd, 1); } if (spawnInfo->stderrFd != 2) { close(2); fd = (spawnInfo->stderrFd == -1) ? devNullFd : spawnInfo->stderrFd; dup2(fd, 2); } if (devNullFd != -1) { close(devNullFd); } /* if child has a serverFd, dup it to the fixed number */ if (spawnInfo->serverFd != -1) { close(CMS_DYNAMIC_LAUNCH_SERVER_FD); dup2(spawnInfo->serverFd, CMS_DYNAMIC_LAUNCH_SERVER_FD); } #if defined(AEI_VDSL_CUSTOMER_NCS) #ifdef SUPPORT_HTTPD_SSL /* httpd second listen fd, dup it if necessary to the fixed number also */ if (spawnInfo->eid == EID_HTTPD || spawnInfo->eid == EID_HTTPSD) { if (spawnInfo->serverFd2 != -1) { close(CMS_DYNAMIC_LAUNCH_SERVER_FD2); dup2(spawnInfo->serverFd2, CMS_DYNAMIC_LAUNCH_SERVER_FD2); } } #endif #endif /* close all of the child's other fd's */ for (i=3; i <= spawnInfo->maxFd; i++) { #if defined(AEI_VDSL_CUSTOMER_NCS) && defined(SUPPORT_HTTPD_SSL) if (i == CMS_DYNAMIC_LAUNCH_SERVER_FD || i == CMS_DYNAMIC_LAUNCH_SERVER_FD2) #else if (i == CMS_DYNAMIC_LAUNCH_SERVER_FD) #endif // if ((spawnInfo->serverFd != -1) && // (i == CMS_DYNAMIC_LAUNCH_SERVER_FD)) { continue; } close(i); } /* * Set all signal handlers back to default action, * in case the parent had set them to SIG_IGN or something. * See kernel/linux/include/asm-mips/signal.h */ signal(SIGHUP, SIG_DFL); if (spawnInfo->inheritSigint == FALSE) { /* * Note: there is a bug in pthread library in the 4.4.2 toolchain * which breaks SIG_IGN inheritance. Apps are advised to set * SIGINT handler explicitly in the app itself. */ signal(SIGINT, SIG_DFL); } signal(SIGQUIT, SIG_DFL); signal(SIGILL, SIG_DFL); signal(SIGTRAP, SIG_DFL); signal(SIGABRT, SIG_DFL); /* same as SIGIOT */ #ifndef DESKTOP_LINUX signal(SIGEMT, SIG_DFL); #endif signal(SIGFPE, SIG_DFL); signal(SIGBUS, SIG_DFL); signal(SIGSEGV, SIG_DFL); signal(SIGSYS, SIG_DFL); signal(SIGPIPE, SIG_DFL); signal(SIGALRM, SIG_DFL); signal(SIGTERM, SIG_DFL); signal(SIGUSR1, SIG_DFL); signal(SIGUSR2, SIG_DFL); signal(SIGCHLD, SIG_DFL); /* same as SIGCLD */ signal(SIGPWR, SIG_DFL); signal(SIGWINCH, SIG_DFL); signal(SIGURG, SIG_DFL); signal(SIGIO, SIG_DFL); /* same as SIGPOLL */ signal(SIGSTOP, SIG_DFL); signal(SIGTSTP, SIG_DFL); signal(SIGCONT, SIG_DFL); signal(SIGTTIN, SIG_DFL); signal(SIGTTOU, SIG_DFL); signal(SIGVTALRM, SIG_DFL); signal(SIGPROF, SIG_DFL); signal(SIGXCPU, SIG_DFL); signal(SIGXFSZ, SIG_DFL); /* overlay child executable over myself */ execv(spawnInfo->exe, argv); /* We should not reach this line. If we do, exec has failed. */ exit(-1); } /* this is the parent */ freeArgs(argv); /* don't need these anymore */ memset(procInfo, 0, sizeof(SpawnedProcessInfo)); procInfo->pid = pid; procInfo->status = PSTAT_RUNNING; if (spawnInfo->spawnMode == SPAWN_AND_WAIT) { CollectProcessInfo collectInfo; collectInfo.collectMode = COLLECT_PID_TIMEOUT; collectInfo.pid = pid; collectInfo.timeout = spawnInfo->timeout; ret = oal_collectProcess(&collectInfo, procInfo); if (ret == CMSRET_TIMED_OUT) { CmsRet r2; cmsLog_debug("pid %d has not exited in %d ms, SIGKILL", spawnInfo->timeout); r2 = oal_signalProcess(pid, SIGKILL); if (r2 != CMSRET_SUCCESS) { cmsLog_error("SIGKILL to pid %d failed with ret=%d", pid, r2); } /* try one more time to collect it */ collectInfo.collectMode = COLLECT_PID_TIMEOUT; collectInfo.pid = pid; collectInfo.timeout = COLLECT_WAIT_INTERVAL_MS; r2 = oal_collectProcess(&collectInfo, procInfo); if (r2 == CMSRET_SUCCESS) { /* we finally go it, otherwise, leave ret at CMSRET_TIMED_OUT */ ret = CMSRET_SUCCESS; } } else if (ret != CMSRET_SUCCESS) { /* some other error with collect */ cmsLog_error("Could not collect pid %d", pid); } } return ret; }
/** Give a single string, allocate and fill in an array of char *'s * each pointing to an individually malloc'd buffer containing a single * argument in the string; the array will end with a char * slot containing NULL. * * This array can be passed to execv. * This array must be freed by calling freeArgs. */ CmsRet parseArgs(const char *cmd, const char *args, char ***argv) { UINT32 numArgs=3, i, len, argIndex=0; UBOOL8 inSpace=TRUE; const char *cmdStr; char **array; len = (args == NULL) ? 0 : strlen(args); /* * First count the number of spaces to determine the number of args * there are in the string. */ for (i=0; i < len; i++) { if ((args[i] == ' ') && (!inSpace)) { numArgs++; inSpace = TRUE; } else { inSpace = FALSE; } } array = (char **) cmsMem_alloc((numArgs) * sizeof(char *), ALLOC_ZEROIZE); if (array == NULL) { return CMSRET_RESOURCE_EXCEEDED; } /* locate the command name, last part of string */ cmdStr = strrchr(cmd, '/'); if (cmdStr == NULL) { cmdStr = cmd; } else { cmdStr++; /* move past the / */ } /* copy the command into argv[0] */ array[argIndex] = cmsMem_alloc(strlen(cmdStr) + 1, ALLOC_ZEROIZE); if (array[argIndex] == NULL) { cmsLog_error("malloc of %d failed", strlen(cmdStr) + 1); freeArgs(array); return CMSRET_RESOURCE_EXCEEDED; } else { strcpy(array[argIndex], cmdStr); argIndex++; } /* * Wow, this is going to be incredibly messy. I have to malloc a buffer * for each arg and copy them in individually. */ inSpace = TRUE; for (i=0; i < len; i++) { if ((args[i] == ' ') && (!inSpace)) { numArgs++; inSpace = TRUE; } else if ((args[i] != ' ') && (inSpace)) { UINT32 startIndex, endIndex; /* * this is the first character I've seen after a space. * Figure out how many letters this arg is, malloc a buffer * to hold it, and copy it into the buffer. */ startIndex = i; endIndex = i; while ((endIndex < len) && (args[endIndex] != ' ')) { endIndex++; } array[argIndex] = cmsMem_alloc(endIndex - startIndex + 1, ALLOC_ZEROIZE); if (array[argIndex] == NULL) { cmsLog_error("malloc of %d failed", endIndex - startIndex + 1); freeArgs(array); return CMSRET_RESOURCE_EXCEEDED; } memcpy(array[argIndex], &args[startIndex], endIndex - startIndex); /* cmsLog_debug("index=%d len=%d (%s)", argIndex, endIndex - startIndex, &args[startIndex]); */ argIndex++; inSpace = FALSE; } } /* check what we did */ i = 0; while (array[i] != NULL) { cmsLog_debug("argv[%d] = %s", i, array[i]); i++; } (*argv) = array; return CMSRET_SUCCESS; }
int main(int argc, char *argv[]) { FILE * file; int i, indirectCount, indirectNode; int zoneCount = 0; int partitionOffset = 0; SUPERBLOCK *diskinfo; INODE *node, *tempNode; DIRECT *direct; ARGSP *argsp; diskinfo = malloc(sizeof(SUPERBLOCK)); node = malloc(sizeof(INODE)); tempNode = malloc(sizeof(INODE)); direct = malloc(sizeof(DIRECT)); argsp = malloc(sizeof(ARGSP)); /* Grab Args */ getArgs(argsp, argc, argv); if(argsp->hflag) { printUsage(); exit(1); } /* Open File */ file = fopen(argsp->image, "r"); if (file == NULL) { perror("Some Error:"); exit (1); } /* Grab Partition offset */ if((partitionOffset = getPartition(file, argsp)) < 0) { fputs("Bad partition\n",stderr); exit(1); } /* Grab node for file */ if(!(node = minInitialize(file, diskinfo, argsp, partitionOffset))) { fputs("File not found\n",stderr); exit(1); } /* current node should be the matching diretory or file */ if((node->mode & FILEMASK & DIRECTORYMASK)) { zoneCount = 0; indirectCount = 0; printf("%s:\n", argsp->path); fseek(file, partitionOffset + diskinfo->zonesize * node->zone[zoneCount], SEEK_SET); for(i = 0; i < node->size / sizeof(DIRECT); i++) { fread(direct, sizeof(DIRECT), 1, file); if(direct->inode) { getNode(tempNode, file, diskinfo, direct->inode, partitionOffset); printItem(tempNode, direct->name); } /* check to see if we are at the end of a zone and need to move to next zone*/ if(((i+1) * sizeof(DIRECT) % diskinfo->zonesize) == 0) { if (zoneCount < REGULAR_ZONES-1) { zoneCount++; fseek(file, partitionOffset + diskinfo->zonesize * node->zone[zoneCount], SEEK_SET); } else { /* jump to indirect block plus offset */ fseek(file, partitionOffset + diskinfo->zonesize * node->zoneindirect + (sizeof(uint32_t) * indirectCount), SEEK_SET); indirectCount++; /* grab new zone value */ fread(&indirectNode, sizeof(uint32_t), 1, file); /* set filepointer to new indirect zone */ fseek(file, partitionOffset + diskinfo->zonesize * indirectNode, SEEK_SET); } } } } else { printItem(node, argsp->path); } freeArgs(argsp); free(argsp); free(direct); free(tempNode); free(node); free(diskinfo); fclose(file); exit(0); }
int main(void) { signal(SIGINT, intHandler); char *command = NULL, *filePath = NULL; char **args = NULL; node *root = NULL; fd_set rfds; struct timeval tv; int retval; while(run) { tv.tv_sec = 1; tv.tv_usec = 0; FD_ZERO(&rfds); FD_SET(0, &rfds); int retval = select(1, &rfds, NULL, NULL, &tv); if(retval == -1) { printf("\nShutting Down\n\n"); return 0; }else if(retval == 0) { continue; } args = getInput(); if(args == NULL) { fflush(stdin); continue; } root = collapseFilePath(args[0]); if(root == NULL) { freeArgs(args); continue; } filePath = getValidFilePath(root); if(filePath == NULL) { freePath(root); freeArgs(args); continue; } char *data = parseData(args[1]); if(data == NULL) { freePath(root); freeArgs(args); free(filePath); continue; } command = (char *) malloc(strlen(filePath) + strlen(data) + 18); if(command == NULL) { printf("ERROR: Not enough memory to malloc the echo command\n"); }else { strncpy(command, "echo ", 6); strncat(command, "\"", 3); strncat(command, data, strlen(data)+1); strncat(command, "\"", 3); strncat(command, " >> ", 5); strncat(command, "\"", 3); strncat(command, filePath, strlen(filePath)+1); strncat(command, "\"", 3); //printf("Command:\n"); //printf("%s\n", command); int result = system(command); if(result == -1) { printf("ERROR: Could not append to file\n"); } printf("SUCCESS\n"); } free(data); free(command); free(filePath); freePath(root); freeArgs(args); } if(command != NULL) free(command); if(filePath != NULL) free(filePath); if(root != NULL) freePath(root); if(args != NULL) freeArgs(args); return 0; }
int PV_Arguments::resetState(int argc, char * argv[], bool allowUnrecognizedArguments) { int status = clearState(); pvAssert(status == PV_SUCCESS); freeArgs(numArgs, args); args = NULL; return initialize(argc, argv, allowUnrecognizedArguments); }