int main(int argc, char** argv) {

  OMX_ERRORTYPE err;
  int argn_dec;
  OMX_STRING full_component_name;

  if(argc < 2){
    display_help();
  } else {
    flagIsOutputExpected = 0;
    argn_dec = 1;
    while (argn_dec < argc) {
      if (*(argv[argn_dec]) == '-') {
        if (flagIsOutputExpected) {
          display_help();
        }
        switch (*(argv[argn_dec] + 1)) {
          case 'h' :
            display_help();
            break;
          case 'o':
            flagIsOutputExpected = 1;
            break;
          default:
            display_help();
        }
      } else {
        if (flagIsOutputExpected) {
          if(strstr(argv[argn_dec], ".yuv") == NULL && strstr(argv[argn_dec], ".rgb") == NULL) {
            output_file = malloc(strlen(argv[argn_dec]) * sizeof(char) + 5);
            strcpy(output_file,argv[argn_dec]);
            strcat(output_file, ".rgb");
          } else {
            output_file = malloc(strlen(argv[argn_dec]) * sizeof(char) + 1);
            strcpy(output_file,argv[argn_dec]);
          }
          flagIsOutputExpected = 0;
        }
      }
      argn_dec++;
    }
  }

  if(output_file==NULL) {
    output_file = malloc(30);
    strcpy(output_file,"default_camera_out.rgb");
  }

  outfile = fopen(output_file, "wb");
  if(outfile == NULL) {
    DEBUG(DEB_LEV_ERR, "Error in opening output file %s\n", output_file);
    exit(1);
  }

  /** setting input picture width to a default value (vga format) for allocation of video videosrc buffers */
  out_width = 176;
  out_height = 144;

  /* Initialize application private data */
  appPriv = malloc(sizeof(appPrivateType));
  appPriv->videosrcEventSem = malloc(sizeof(tsem_t));
  appPriv->eofSem = malloc(sizeof(tsem_t));
  tsem_init(appPriv->videosrcEventSem, 0);
  tsem_init(appPriv->eofSem, 0);

  DEBUG(DEB_LEV_SIMPLE_SEQ, "Init the Omx core\n");
  err = OMX_Init();
  if (err != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "The OpenMAX core can not be initialized. Exiting...\n");
    exit(1);
  } else {
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Omx core is initialized \n");
  }

  test_OpenClose(COMPONENT_NAME);
  DEBUG(DEFAULT_MESSAGES, "------------------------------------\n");


  full_component_name = (OMX_STRING) malloc(sizeof(char*) * OMX_MAX_STRINGNAME_SIZE);
  strcpy(full_component_name, COMPONENT_NAME);


  DEBUG(DEFAULT_MESSAGES, "The component selected for capturing is %s\n", full_component_name);

  /** getting video videosrc handle */
  err = OMX_GetHandle(&appPriv->videosrchandle, full_component_name, NULL, &videosrccallbacks);
  if(err != OMX_ErrorNone){
    DEBUG(DEB_LEV_ERR, "No video videosrc component found. Exiting...\n");
    exit(1);
  } else {
    DEBUG(DEFAULT_MESSAGES, "Found The component for capturing is %s\n", full_component_name);
  }

  /** output buffer size calculation based on input dimension speculation */
  buffer_out_size = out_width * out_height * 3; //yuv420 format -- bpp = 12
  DEBUG(DEB_LEV_SIMPLE_SEQ, "\n buffer_out_size : %d \n", (int)buffer_out_size);

  /** sending command to video videosrc component to go to idle state */
  err = OMX_SendCommand(appPriv->videosrchandle, OMX_CommandStateSet, OMX_StateIdle, NULL);

  pOutBuffer1 = pOutBuffer2 = NULL;
  err = OMX_AllocateBuffer(appPriv->videosrchandle, &pOutBuffer1, 0, NULL, buffer_out_size);
  err = OMX_AllocateBuffer(appPriv->videosrchandle, &pOutBuffer2, 0, NULL, buffer_out_size);


  DEBUG(DEB_LEV_SIMPLE_SEQ, "Before locking on idle wait semaphore\n");
  tsem_down(appPriv->videosrcEventSem);
  DEBUG(DEB_LEV_SIMPLE_SEQ, "videosrc Sem free\n");

  /** sending command to video videosrc component to go to executing state */
  err = OMX_SendCommand(appPriv->videosrchandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
  tsem_down(appPriv->videosrcEventSem);

  err = OMX_FillThisBuffer(appPriv->videosrchandle, pOutBuffer1);
  err = OMX_FillThisBuffer(appPriv->videosrchandle, pOutBuffer2);

  DEBUG(DEFAULT_MESSAGES,"Waiting for  EOS\n");

  /*Capture video for 10 seconds*/
  sleep(10);
  bEOS = OMX_TRUE;
  DEBUG(DEFAULT_MESSAGES,"Set  EOS\n");
  sleep(1);
  //tsem_down(appPriv->eofSem);

  DEBUG(DEFAULT_MESSAGES, "The execution of the video capturing process is terminated\n");

  /** state change of all components from executing to idle */
  err = OMX_SendCommand(appPriv->videosrchandle, OMX_CommandStateSet, OMX_StateIdle, NULL);

  tsem_down(appPriv->videosrcEventSem);


  DEBUG(DEFAULT_MESSAGES, "All video components Transitioned to Idle\n");

  /** sending command to all components to go to loaded state */
  err = OMX_SendCommand(appPriv->videosrchandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);


  /** freeing buffers of video videosrc input ports */
  DEBUG(DEB_LEV_PARAMS, "Free Video dec output ports\n");
  err = OMX_FreeBuffer(appPriv->videosrchandle, 0, pOutBuffer1);
  err = OMX_FreeBuffer(appPriv->videosrchandle, 0, pOutBuffer2);

  tsem_down(appPriv->videosrcEventSem);
  DEBUG(DEB_LEV_SIMPLE_SEQ, "All components released\n");

  OMX_FreeHandle(appPriv->videosrchandle);

  DEBUG(DEB_LEV_SIMPLE_SEQ, "video dec freed\n");

  OMX_Deinit();

  DEBUG(DEFAULT_MESSAGES, "All components freed. Closing...\n");
  free(appPriv->videosrcEventSem);

  free(appPriv->eofSem);
  free(appPriv);

  /** closing the output file */
  fclose(outfile);

  return 0;
}
예제 #2
0
파일: sar.c 프로젝트: alemic/sysstat
/*
 ***************************************************************************
 * Main entry to the sar program.
 ***************************************************************************
 */
int main(int argc, char **argv)
{
	int i, rc, opt = 1, args_idx = 2;
	int fd[2];
	int day_offset = 0;
	char from_file[MAX_FILE_LEN], to_file[MAX_FILE_LEN];
	char ltemp[20];

	/* Get HZ */
	get_HZ();

	/* Compute page shift in kB */
	get_kb_shift();

	from_file[0] = to_file[0] = '\0';

#ifdef USE_NLS
	/* Init National Language Support */
	init_nls();
#endif

	tm_start.use = tm_end.use = FALSE;
	
	/* Allocate and init activity bitmaps */
	allocate_bitmaps(act);

	init_structures();

	/* Process options */
	while (opt < argc) {

		if (!strcmp(argv[opt], "-I")) {
			if (argv[++opt]) {
				/* Parse -I option */
				if (parse_sar_I_opt(argv, &opt, act)) {
					usage(argv[0]);
				}
			}
			else {
				usage(argv[0]);
			}
		}

		else if (!strcmp(argv[opt], "-P")) {
			/* Parse -P option */
			if (parse_sa_P_opt(argv, &opt, &flags, act)) {
				usage(argv[0]);
			}
		}

		else if (!strcmp(argv[opt], "-o")) {
			/* Save stats to a file */
			if ((argv[++opt]) && strncmp(argv[opt], "-", 1) &&
			    (strspn(argv[opt], DIGITS) != strlen(argv[opt]))) {
				strncpy(to_file, argv[opt++], MAX_FILE_LEN);
				to_file[MAX_FILE_LEN - 1] = '\0';
			}
			else {
				strcpy(to_file, "-");
			}
		}

		else if (!strcmp(argv[opt], "-f")) {
			/* Read stats from a file */
			if ((argv[++opt]) && strncmp(argv[opt], "-", 1) &&
			    (strspn(argv[opt], DIGITS) != strlen(argv[opt]))) {
				strncpy(from_file, argv[opt++], MAX_FILE_LEN);
				from_file[MAX_FILE_LEN - 1] = '\0';
			}
			else {
				set_default_file(&rectime, from_file, day_offset);
			}
		}

		else if (!strcmp(argv[opt], "-s")) {
			/* Get time start */
			if (parse_timestamp(argv, &opt, &tm_start, DEF_TMSTART)) {
				usage(argv[0]);
			}
		}

		else if (!strcmp(argv[opt], "-e")) {
			/* Get time end */
			if (parse_timestamp(argv, &opt, &tm_end, DEF_TMEND)) {
				usage(argv[0]);
			}
		}

		else if (!strcmp(argv[opt], "-h")) {
			/* Display help message */
			display_help(argv[0]);
		}

		else if (!strcmp(argv[opt], "-i")) {
			if (!argv[++opt] || (strspn(argv[opt], DIGITS) != strlen(argv[opt]))) {
				usage(argv[0]);
			}
			interval = atol(argv[opt++]);
			if (interval < 1) {
				usage(argv[0]);
			}
			flags |= S_F_INTERVAL_SET;
		}

		else if (!strcmp(argv[opt], "-m")) {
			if (argv[++opt]) {
				/* Parse option -m */
				if (parse_sar_m_opt(argv, &opt, act)) {
					usage(argv[0]);
				}
			}
			else {
				usage(argv[0]);
			}
		}

		else if (!strcmp(argv[opt], "-n")) {
			if (argv[++opt]) {
				/* Parse option -n */
				if (parse_sar_n_opt(argv, &opt, act)) {
					usage(argv[0]);
				}
			}
			else {
				usage(argv[0]);
			}
		}
		
		else if ((strlen(argv[opt]) > 1) &&
			 (strlen(argv[opt]) < 4) &&
			 !strncmp(argv[opt], "-", 1) &&
			 (strspn(argv[opt] + 1, DIGITS) == (strlen(argv[opt]) - 1))) {
			day_offset = atoi(argv[opt++] + 1);
		}

		else if (!strncmp(argv[opt], "-", 1)) {
			/* Other options not previously tested */
			if ((rc = parse_sar_opt(argv, &opt, act, &flags, C_SAR)) != 0) {
				if (rc == 1) {
					usage(argv[0]);
				}
				exit(1);
			}
			opt++;
		}

		else if (interval < 0) {
			/* Get interval */
			if (strspn(argv[opt], DIGITS) != strlen(argv[opt])) {
				usage(argv[0]);
			}
			interval = atol(argv[opt++]);
			if (interval < 0) {
				usage(argv[0]);
			}
		}

		else {
			/* Get count value */
			if ((strspn(argv[opt], DIGITS) != strlen(argv[opt])) ||
			    !interval) {
				usage(argv[0]);
			}
			if (count) {
				/* Count parameter already set */
				usage(argv[0]);
			}
			count = atol(argv[opt++]);
			if (count < 1) {
				usage(argv[0]);
			}
		}
	}

	/* 'sar' is equivalent to 'sar -f' */
	if ((argc == 1) ||
	    ((interval < 0) && !from_file[0] && !to_file[0])) {
		set_default_file(&rectime, from_file, day_offset);
	}

	if (tm_start.use && tm_end.use && (tm_end.tm_hour < tm_start.tm_hour)) {
		tm_end.tm_hour += 24;
	}

	/*
	 * Check option dependencies.
	 */
	/* You read from a file OR you write to it... */
	if (from_file[0] && to_file[0]) {
		fprintf(stderr, _("-f and -o options are mutually exclusive\n"));
		exit(1);
	}
	/* Use time start or option -i only when reading stats from a file */
	if ((tm_start.use || INTERVAL_SET(flags)) && !from_file[0]) {
		fprintf(stderr,
			_("Not reading from a system activity file (use -f option)\n"));
		exit(1);
	}
	/* Don't print stats since boot time if -o or -f options are used */
	if (!interval && (from_file[0] || to_file[0])) {
		usage(argv[0]);
	}
	
	/* Cannot enter a day shift with -o option */
	if (to_file[0] && day_offset) {
		usage(argv[0]);
	}

	if (USE_PRETTY_OPTION(flags)) {
		dm_major = get_devmap_major();
	}
	
	if (!count) {
		/*
		 * count parameter not set: Display all the contents of the file
		 * or generate a report continuously.
		 */
		count = -1;
	}

	/* Default is CPU activity... */
	select_default_activity(act);
	
	/* Reading stats from file: */
	if (from_file[0]) {
		if (interval < 0) {
			interval = 1;
		}

		/* Read stats from file */
		read_stats_from_file(from_file);
		
		/* Free stuctures and activity bitmaps */
		free_bitmaps(act);
		free_structures(act);

		return 0;
	}

	/* Reading stats from sadc: */

	/* Create anonymous pipe */
	if (pipe(fd) == -1) {
		perror("pipe");
		exit(4);
	}

	switch (fork()) {

	case -1:
		perror("fork");
		exit(4);
		break;

	case 0: /* Child */
		if (dup2(fd[1], STDOUT_FILENO) < 0) {
			perror("dup2");
			exit(4);
		}
		CLOSE_ALL(fd);

		/*
		 * Prepare options for sadc.
		 */
		/* Program name */
		salloc(0, SADC);

		/* Interval value */
		if (interval < 0) {
			usage(argv[0]);
		}
		else if (!interval) {
			strcpy(ltemp, "1");
		}
		else {
			sprintf(ltemp, "%ld", interval);
		}
		salloc(1, ltemp);

		/* Count number */
		if (count >= 0) {
			sprintf(ltemp, "%ld", count + 1);
			salloc(args_idx++, ltemp);
		}

		/* Flags to be passed to sadc */
		salloc(args_idx++, "-z");
		
		/* Writing data to a file (option -o) */
		if (to_file[0]) {
			/* Collect all possible activities (option -S XALL for sadc) */
			salloc(args_idx++, "-S");
			salloc(args_idx++, K_XALL);
			/* Outfile arg */
			salloc(args_idx++, to_file);
		}
		else {
			/*
			 * If option -o hasn't been used, then tell sadc
			 * to collect only activities that will be displayed.
			 */
			int act_id = 0;
			
			for (i = 0; i < NR_ACT; i++) {
				if (IS_SELECTED(act[i]->options)) {
					act_id |= act[i]->group;
				}
			}
			if (act_id) {
				act_id <<= 8;
				snprintf(ltemp, 19, "%d", act_id);
				ltemp[19] = '\0';
				salloc(args_idx++, "-S");
				salloc(args_idx++, ltemp);
			}
		}

		/* Last arg is NULL */
		args[args_idx] = NULL;

		/* Call now the data collector */
		execv(SADC_PATH, args);
		execvp(SADC, args);
		/*
		 * Note: Don't use execl/execlp since we don't have a fixed number of
		 * args to give to sadc.
		 */
		fprintf(stderr, _("Cannot find the data collector (%s)\n"), SADC);
		perror("exec");
		exit(4);
		break;

	default: /* Parent */
		if (dup2(fd[0], STDIN_FILENO) < 0) {
			perror("dup2");
			exit(4);
		}
		CLOSE_ALL(fd);

		/* Get now the statistics */
		read_stats();

		break;
	}

	/* Free structures and activity bitmaps */
	free_bitmaps(act);
	free_structures(act);

	return 0;
}
예제 #3
0
int main (int argc, char **argv)
{
    register char **fp = filelist;
    register char **incp = includedirs;
    register char *p;
    register struct inclist *ip;
    char *makefile = NULL;
    struct filepointer *filecontent;
    struct symtab *psymp = predefs;
    const char *endmarker = NULL;
    char *defincdir = NULL;
    char **undeflist = NULL;
    int i, numundefs = 0;

#if defined (INITIALIZE)	// initialization code
    INITIALIZE;
#endif

    ProgramName = argv[0];

    while (psymp->s_name)
    {
        define2 (psymp->s_name, psymp->s_value, &maininclist);
        psymp++;
    }
    if (argc == 2 && argv[1][0] == '@')
    {
        struct stat ast;
        int afd;
        char *args;
        char **nargv;
        int nargc;
        char quotechar = '\0';

        nargc = 1;
        if ((afd = open (argv[1] + 1, O_RDONLY)) < 0)
            fatalerr ("cannot open \"%s\"\n", argv[1] + 1);
        fstat (afd, &ast);
        args = (char *) malloc (ast.st_size + 1);
        if ((ast.st_size = read (afd, args, ast.st_size)) < 0)
            fatalerr ("failed to read %s\n", argv[1] + 1);
        args[ast.st_size] = '\0';
        close (afd);
        for (p = args; *p; p++)
        {
            if (quotechar)
            {
                if (quotechar == '\\' ||
                    (*p == quotechar && p[-1] != '\\'))
                    quotechar = '\0';
                continue;
            }
            switch (*p)
            {
                case '\\':
                case '"':
                case '\'':
                    quotechar = *p;
                    break;
                case ' ':
                case '\n':
                    *p = '\0';
                    if (p > args && p[-1])
                        nargc++;
                    break;
            }
        }
        if (p[-1])
            nargc++;
        nargv = (char **) malloc (nargc * sizeof (char *));

        nargv[0] = argv[0];
        argc = 1;
        for (p = args; argc < nargc; p += strlen (p) + 1)
            if (*p)
                nargv[argc++] = p;
        argv = nargv;
    }
    for (argc--, argv++; argc; argc--, argv++)
    {
        /* if looking for endmarker then check before parsing */
        if (endmarker && strcmp (endmarker, *argv) == 0)
        {
            endmarker = NULL;
            continue;
        }
        if (**argv != '-')
        {
            /* treat +thing as an option for C++ */
            if (endmarker && **argv == '+')
                continue;
            *fp++ = argv[0];
            continue;
        }
        switch (argv[0][1])
        {
            case '-':
                endmarker = &argv[0][2];
                if (endmarker[0] == '\0')
                    endmarker = "--";
                break;
            case 'D':
                if (argv[0][2] == '\0')
                {
                    argv++;
                    argc--;
                }
                for (p = argv[0] + 2; *p; p++)
                    if (*p == '=')
                    {
                        *p = ' ';
                        break;
                    }
                define (argv[0] + 2, &maininclist);
                break;
            case 'I':
                if (incp >= includedirs + MAXDIRS)
                    fatalerr ("Too many -I flags.\n");
                *incp++ = argv[0] + 2;
                if (**(incp - 1) == '\0')
                {
                    *(incp - 1) = *(++argv);
                    argc--;
                }
                break;
            case 'U':
                /* Undef's override all -D's so save them up */
                numundefs++;
                if (numundefs == 1)
                    undeflist = (char **)malloc (sizeof (char *));
                else
                    undeflist = (char **)realloc (undeflist, numundefs * sizeof (char *));

                if (argv[0][2] == '\0')
                {
                    argv++;
                    argc--;
                }
                undeflist[numundefs - 1] = argv[0] + 2;
                break;
            case 'Y':
                defincdir = argv[0] + 2;
                break;
                /* do not use if endmarker processing */
            case 'a':
                if (endmarker)
                    break;
                opt_append = true;
                break;
            case 'b':
                if (endmarker)
                    break;
                opt_backup = true;
                break;
            case 'c':
                if (endmarker)
                    break;
                opt_create = true;
                break;
            case 'r':
                if (endmarker)
                    break;
                opt_remove_prefix = true;
                break;
            case 'w':
                if (endmarker)
                    break;
                if (argv[0][2] == '\0')
                {
                    argv++;
                    argc--;
                    width = atoi (argv[0]);
                }
                else
                    width = atoi (argv[0] + 2);
                break;
            case 'o':
                if (endmarker)
                    break;
                if (argv[0][2] == '\0')
                {
                    argv++;
                    argc--;
                    objsuffix = argv[0];
                }
                else
                    objsuffix = argv[0] + 2;
                break;
            case 'p':
                if (endmarker)
                    break;
                if (argv[0][2] == '\0')
                {
                    argv++;
                    argc--;
                    objprefix = argv[0];
                }
                else
                    objprefix = argv[0] + 2;
                break;
            case 'S':
                if (endmarker)
                    break;
                opt_sysincludes = true;
                break;
            case 'v':
                if (endmarker)
                    break;
                opt_verbose = true;
#ifdef CS_DEBUG
                if (argv[0][2])
                    _debugmask = atoi (argv[0] + 2);
#endif
                break;
            case 's':
                if (endmarker)
                    break;
                startat = argv[0] + 2;
                if (*startat == '\0')
                {
                    startat = *(++argv);
                    argc--;
                }
                if (*startat != '#')
                    fatalerr ("-s flag's value should start %s\n",
                              "with '#'.");
                break;
            case 'f':
                if (endmarker)
                    break;
                makefile = argv[0] + 2;
                if (*makefile == '\0')
                {
                    makefile = *(++argv);
                    argc--;
                }
                break;

            case 'm':
                opt_warn_multiple = true;
                break;

                /* Ignore -O, -g so we can just pass ${CFLAGS} to
                 makedepend
                 */
            case 'O':
            case 'g':
                break;
            case 'h':
                if (endmarker)
                    break;
                display_help ();
                return 0;
            case 'V':
                if (endmarker)
                    break;
                display_version ();
                return 0;
            default:
                if (endmarker)
                    break;
                /* fatalerr("unknown opt = %s\n", argv[0]); */
                warning ("ignoring option %s\n", argv[0]);
        }
    }
    /* Now do the undefs from the command line */
    for (i = 0; i < numundefs; i++)
        undefine (undeflist[i], &maininclist);
    if (numundefs > 0)
        free (undeflist);

    if (!defincdir)
    {
#ifdef PREINCDIR
        add_include (PREINCDIR, incp);
#endif
#if defined (__GNUC__) || defined (_WIN32)
        add_include (
#  if defined (__GNUC__)
       getenv ("C_INCLUDE_PATH"),
#  else
       getenv ("INCLUDE"),
#  endif
       incp);
#else /* !__GNUC__, does not use INCLUDEDIR at all */
        if (incp >= includedirs + MAXDIRS)
            fatalerr ("Too many -I flags.\n");
        *incp++ = INCLUDEDIR;
#endif

#ifdef POSTINCDIR
        add_include (POSTINCDIR, incp);
#endif
    }
    else if (*defincdir)
        add_include (defincdir, incp);

    /* if nothing to do, abort */
    if (!*filelist)
        fatalerr ("No files specified, try \"makedep -h\"\n");

    redirect (startat, makefile);

    /* catch signals */
#ifdef USGISH
    /*  should really reset SIGINT to SIG_IGN if it was.  */
#ifdef SIGHUP
    signal (SIGHUP, sighandler);
#endif
    signal (SIGINT, sighandler);
#ifdef SIGQUIT
    signal (SIGQUIT, sighandler);
#endif
    signal (SIGILL, sighandler);
#ifdef SIGBUS
    signal (SIGBUS, sighandler);
#endif
    signal (SIGSEGV, sighandler);
#ifdef SIGSYS
    signal (SIGSYS, sighandler);
#endif
#else
    sig_act.sa_handler = sighandler;
#ifdef _POSIX_SOURCE
    sigemptyset (&sig_act.sa_mask);
    sigaddset (&sig_act.sa_mask, SIGINT);
    sigaddset (&sig_act.sa_mask, SIGQUIT);
#ifdef SIGBUS
    sigaddset (&sig_act.sa_mask, SIGBUS);
#endif
    sigaddset (&sig_act.sa_mask, SIGILL);
    sigaddset (&sig_act.sa_mask, SIGSEGV);
    sigaddset (&sig_act.sa_mask, SIGHUP);
    sigaddset (&sig_act.sa_mask, SIGPIPE);
#ifdef SIGSYS
    sigaddset (&sig_act.sa_mask, SIGSYS);
#endif
#else
    sig_act.sa_mask = ((1 << (SIGINT - 1))
#ifdef SIGQUIT
                       | (1 << (SIGQUIT - 1))
#endif
#ifdef SIGBUS
                       | (1 << (SIGBUS - 1))
#endif
                       | (1 << (SIGILL - 1))
                       | (1 << (SIGSEGV - 1))
#ifdef SIGHUP
                       | (1 << (SIGHUP - 1))
#endif
#ifdef SIGPIPE
                       | (1 << (SIGPIPE - 1))
#endif
#ifdef SIGSYS
                       | (1 << (SIGSYS - 1))
#endif
                      );
#endif /* _POSIX_SOURCE */
    sig_act.sa_flags = 0;
#ifdef SIGHUP
    sigaction (SIGHUP, &sig_act, (struct sigaction *) 0);
#endif
    sigaction (SIGINT, &sig_act, (struct sigaction *) 0);
#ifdef SIGQUIT
    sigaction (SIGQUIT, &sig_act, (struct sigaction *) 0);
#endif
    sigaction (SIGILL, &sig_act, (struct sigaction *) 0);
#ifdef SIGBUS
    sigaction (SIGBUS, &sig_act, (struct sigaction *) 0);
#endif
    sigaction (SIGSEGV, &sig_act, (struct sigaction *) 0);
#ifdef SIGSYS
    sigaction (SIGSYS, &sig_act, (struct sigaction *) 0);
#endif
#endif /* USGISH */

    /*
     * now peruse through the list of files.
     */
    for (fp = filelist; *fp; fp++)
    {
        filecontent = getfile (*fp);
        ip = newinclude (*fp, (char *) NULL);

        find_includes (filecontent, ip, ip, 0, false);
        freefile (filecontent);
        recursive_pr_include (ip, ip->i_file, base_name (*fp));
        inc_clean ();
    }
    if (opt_printed)
        printf ("\n");
    return 0;
}
예제 #4
0
/**
 * Main daemon routine
 */
int main( int argc, char **argv )
{
    int            c, option_index = 0;
    char          *bin = basename( argv[0] );

    char           config_file[MAX_OPT_LEN] = "";

    enum { ACTION_NONE, ACTION_LIST, ACTION_RESTORE } action = ACTION_NONE;
    int            force_log_level = FALSE;
    int            log_level = 0;

    int            rc;
    char           err_msg[4096];
    robinhood_config_t config;
    int chgd = 0;
    char    badcfg[RBH_PATH_MAX];

    /* parse command line options */
    while ( ( c = getopt_long( argc, argv, SHORT_OPT_STRING, option_tab,
                               &option_index ) ) != -1 )
    {
        switch ( c )
        {
        case 'L':
            if ( (action != ACTION_NONE) && (action != ACTION_LIST) )
                fprintf( stderr, "WARNING: only a single action (--list or --restore) is expected\n"
                                 "on command line. '--restore' will be ignored.\n" );
            action = ACTION_LIST;
            break;
        case 'R':
            if ( (action != ACTION_NONE) && (action != ACTION_RESTORE) )
                fprintf( stderr, "WARNING: only a single action (--list or --restore) is expected\n"
                                 "on command line. '--list' will be ignored.\n" );
            action = ACTION_RESTORE;
            break;
        case 'f':
            rh_strncpy(config_file, optarg, MAX_OPT_LEN);
            break;
        case 'l':
            force_log_level = TRUE;
            log_level = str2debuglevel( optarg );
            if ( log_level == -1 )
            {
                fprintf( stderr,
                         "Unsupported log level '%s'. CRIT, MAJOR, EVENT, VERB, DEBUG or FULL expected.\n",
                         optarg );
                exit( 1 );
            }
            break;
        case 'h':
            display_help( bin );
            exit( 0 );
            break;
        case 'V':
            display_version( bin );
            exit( 0 );
            break;
        case ':':
        case '?':
        default:
            display_help( bin );
            exit( 1 );
            break;
        }
    }

    /* 1 expected argument: path */
    if ( optind != argc - 1 )
    {
        fprintf( stderr, "Error: missing mandatory argument on command line: <path|fid>\n" );
        exit( 1 );
    }
    rh_strncpy(path_filter, argv[optind], RBH_PATH_MAX);

    /* get default config file, if not specified */
    if (SearchConfig(config_file, config_file, &chgd, badcfg, MAX_OPT_LEN) != 0)
    {
        fprintf(stderr, "No config file (or too many) found matching %s\n", badcfg);
        exit(2);
    }
    else if (chgd)
    {
        fprintf(stderr, "Using config file '%s'.\n", config_file );
    }

    /* only read ListMgr config */
    if ( ReadRobinhoodConfig( 0, config_file, err_msg, &config, FALSE ) )
    {
        fprintf( stderr, "Error reading configuration file '%s': %s\n", config_file, err_msg );
        exit( 1 );
    }
    process_config_file = config_file;

    /* set global configuration */
    global_config = config.global_config;

    /* set policies info */
    policies = config.policies;

    if ( force_log_level )
        config.log_config.debug_level = log_level;

    /* XXX HOOK: Set logging to stderr */
    strcpy( config.log_config.log_file, "stderr" );
    strcpy( config.log_config.report_file, "stderr" );
    strcpy( config.log_config.alert_file, "stderr" );

    /* Initialize logging */
    rc = InitializeLogs( bin, &config.log_config );
    if ( rc )
    {
        fprintf( stderr, "Error opening log files: rc=%d, errno=%d: %s\n",
                 rc, errno, strerror( errno ) );
        exit( rc );
    }

    /* Initialize Filesystem access */
    rc = InitFS();
    if (rc)
        exit(rc);

    /* Initialize list manager */
    rc = ListMgr_Init( &config.lmgr_config, FALSE );
    if ( rc )
    {
        DisplayLog( LVL_CRIT, LOGTAG, "Error %d initializing list manager", rc );
        exit( rc );
    }
    else
        DisplayLog( LVL_DEBUG, LOGTAG, "ListManager successfully initialized" );

    if ( CheckLastFS(  ) != 0 )
        exit( 1 );

    /* Create database access */
    rc = ListMgr_InitAccess( &lmgr );
    if ( rc )
    {
        DisplayLog( LVL_CRIT, LOGTAG, "Error %d: cannot connect to database", rc );
        exit( rc );
    }

#ifdef _HSM_LITE
    rc = Backend_Start( &config.backend_config, 0 );
    if ( rc )
    {
        DisplayLog( LVL_CRIT, LOGTAG, "Error initializing backend" );
        exit( 1 );
    }
#endif

    /* perform the action */
    switch( action )
    {
        case ACTION_LIST:
            rc= list_rm();
            break;
        case ACTION_RESTORE:
            rc = undo_rm();
            break;
        case ACTION_NONE:
            display_help( bin );
            rc = 1;
            break;
        default:
            fprintf(stderr, "Unexpected action (action code=%#x)\n", action );
            display_help( bin );
            rc = EINVAL;
            break;
    }

    ListMgr_CloseAccess( &lmgr );

    return rc;

}
예제 #5
0
파일: bti.c 프로젝트: pferor/bti
int main(int argc, char *argv[], char *envp[])
{
	static const struct option options[] = {
		{ "debug", 0, NULL, 'd' },
		{ "verbose", 0, NULL, 'V' },
		{ "account", 1, NULL, 'a' },
		{ "password", 1, NULL, 'p' },
		{ "host", 1, NULL, 'H' },
		{ "proxy", 1, NULL, 'P' },
		{ "action", 1, NULL, 'A' },
		{ "user", 1, NULL, 'u' },
		{ "group", 1, NULL, 'G' },
		{ "logfile", 1, NULL, 'L' },
		{ "shrink-urls", 0, NULL, 's' },
		{ "help", 0, NULL, 'h' },
		{ "bash", 0, NULL, 'b' },
		{ "background", 0, NULL, 'B' },
		{ "dry-run", 0, NULL, 'n' },
		{ "page", 1, NULL, 'g' },
		{ "column", 1, NULL, 'o' },
		{ "version", 0, NULL, 'v' },
		{ "config", 1, NULL, 'c' },
		{ "replyto", 1, NULL, 'r' },
		{ "retweet", 1, NULL, 'w' },
		{ }
	};
    struct stat s;
	struct session *session;
	pid_t child;
	char *tweet;
	static char password[80];
	int retval = 0;
	int option;
	char *http_proxy;
	char *home;
	const char *config_file;
	time_t t;
	int page_nr;

	debug = 0;

	session = session_alloc();
	if (!session) {
		fprintf(stderr, "no more memory...\n");
		return -1;
	}

	/* get the current time so that we can log it later */
	time(&t);
	session->time = strdup(ctime(&t));
	session->time[strlen(session->time)-1] = 0x00;

	/*
	 * Get the home directory so we can try to find a config file.
	 * If we have no home dir set up, look in /etc/bti
	 */
	home = getenv("HOME");
	if (home) {
		/* We have a home dir, so this might be a user */
		session->homedir = strdup(home);

        /* if '.config/' exists, use XDG standard, else don't */
        if (-1 == stat("~/.config"), &s) {
            config_file = config_xdg_default;
        } else {
    		config_file = config_user_default;
        }
	} else {
		session->homedir = strdup("");
		config_file = config_default;
	}

	/* set up a default config file location (traditionally "~/.bti" or "~/.config/bti") */
	session->configfile = zalloc(strlen(session->homedir) + strlen(config_file) + 7);
	sprintf(session->configfile, "%s/%s", session->homedir, config_file);

	/* Set environment variables first, before reading command line options
	 * or config file values. */
	http_proxy = getenv("http_proxy");
	if (http_proxy) {
		if (session->proxy)
			free(session->proxy);
		session->proxy = strdup(http_proxy);
		dbg("http_proxy = %s\n", session->proxy);
	}

	bti_parse_configfile(session);

	while (1) {
		option = getopt_long_only(argc, argv,
					  "dp:P:H:a:A:u:c:hg:o:G:sr:nVvw:",
					  options, NULL);
		if (option == -1)
			break;
		switch (option) {
		case 'd':
			debug = 1;
			break;
		case 'V':
			session->verbose = 1;
			break;
		case 'a':
			if (session->account)
				free(session->account);
			session->account = strdup(optarg);
			dbg("account = %s\n", session->account);
			break;
		case 'g':
			page_nr = atoi(optarg);
			dbg("page = %d\n", page_nr);
			session->page = page_nr;
			break;
		case 'o':
			session->column_output = atoi(optarg);
			dbg("column_output = %d\n", session->column_output);
			break;
		case 'r':
			session->replyto = strdup(optarg);
			dbg("in_reply_to_status_id = %s\n", session->replyto);
			break;
		case 'w':
			session->retweet = strdup(optarg);
			dbg("Retweet ID = %s\n", session->retweet);
			break;
		case 'p':
			if (session->password)
				free(session->password);
			session->password = strdup(optarg);
			dbg("password = %s\n", session->password);
			break;
		case 'P':
			if (session->proxy)
				free(session->proxy);
			session->proxy = strdup(optarg);
			dbg("proxy = %s\n", session->proxy);
			break;
		case 'A':
			if (strcasecmp(optarg, "update") == 0)
				session->action = ACTION_UPDATE;
			else if (strcasecmp(optarg, "friends") == 0)
				session->action = ACTION_FRIENDS;
			else if (strcasecmp(optarg, "user") == 0)
				session->action = ACTION_USER;
			else if (strcasecmp(optarg, "replies") == 0)
				session->action = ACTION_REPLIES;
			else if (strcasecmp(optarg, "public") == 0)
				session->action = ACTION_PUBLIC;
			else if (strcasecmp(optarg, "group") == 0)
				session->action = ACTION_GROUP;
			else if (strcasecmp(optarg, "retweet") == 0)
				session->action = ACTION_RETWEET;
			else
				session->action = ACTION_UNKNOWN;
			dbg("action = %d\n", session->action);
			break;
		case 'u':
			if (session->user)
				free(session->user);
			session->user = strdup(optarg);
			dbg("user = %s\n", session->user);
			break;

		case 'G':
			if (session->group)
				free(session->group);
			session->group = strdup(optarg);
			dbg("group = %s\n", session->group);
			break;
		case 'L':
			if (session->logfile)
				free(session->logfile);
			session->logfile = strdup(optarg);
			dbg("logfile = %s\n", session->logfile);
			break;
		case 's':
			session->shrink_urls = 1;
			break;
		case 'H':
			if (session->hosturl)
				free(session->hosturl);
			if (session->hostname)
				free(session->hostname);
			if (strcasecmp(optarg, "twitter") == 0) {
				session->host = HOST_TWITTER;
				session->hosturl = strdup(twitter_host);
				session->hostname = strdup(twitter_name);
			} else if (strcasecmp(optarg, "identica") == 0) {
				session->host = HOST_IDENTICA;
				session->hosturl = strdup(identica_host);
				session->hostname = strdup(identica_name);
			} else {
				session->host = HOST_CUSTOM;
				session->hosturl = strdup(optarg);
				session->hostname = strdup(optarg);
			}
			dbg("host = %d\n", session->host);
			break;
		case 'b':
			session->bash = 1;
			/* fall-through intended */
		case 'B':
			session->background = 1;
			break;
		case 'c':
			if (session->configfile)
				free(session->configfile);
			session->configfile = strdup(optarg);
			dbg("configfile = %s\n", session->configfile);

			/*
			 * read the config file now.  Yes, this could override
			 * previously set options from the command line, but
			 * the user asked for it...
			 */
			bti_parse_configfile(session);
			break;
		case 'h':
			display_help();
			goto exit;
		case 'n':
			session->dry_run = 1;
			break;
		case 'v':
			display_version();
			goto exit;
		default:
			display_help();
			goto exit;
		}
	}

	session_readline_init(session);
	/*
	 * Show the version to make it easier to determine what
	 * is going on here
	 */
	if (debug)
		display_version();

	if (session->host == HOST_TWITTER) {
		if (!session->consumer_key || !session->consumer_secret) {
			if (session->action == ACTION_USER ||
					session->action == ACTION_PUBLIC) {
				/*
				 * Some actions may still work without
				 * authentication
				 */
				session->guest = 1;
			} else {
				fprintf(stderr,
						"Twitter no longer supports HTTP basic authentication.\n"
						"Both consumer key, and consumer secret are required"
						" for bti in order to behave as an OAuth consumer.\n");
				goto exit;
			}
		}
		if (session->action == ACTION_GROUP) {
			fprintf(stderr, "Groups only work in Identi.ca.\n");
			goto exit;
		}
	} else {
		if (!session->consumer_key || !session->consumer_secret)
			session->no_oauth = 1;
	}

	if (session->no_oauth) {
		if (!session->account) {
			fprintf(stdout, "Enter account for %s: ",
				session->hostname);
			session->account = session->readline(NULL);
		}
		if (!session->password) {
			read_password(password, sizeof(password),
				      session->hostname);
			session->password = strdup(password);
		}
	} else if (!session->guest) {
		if (!session->access_token_key ||
		    !session->access_token_secret) {
			request_access_token(session);
			goto exit;
		}
	}

	if (session->action == ACTION_UNKNOWN) {
		fprintf(stderr, "Unknown action, valid actions are:\n"
			"'update', 'friends', 'public', 'replies', 'group' or 'user'.\n");
		goto exit;
	}

	if (session->action == ACTION_GROUP && !session->group) {
		fprintf(stdout, "Enter group name: ");
		session->group = session->readline(NULL);
	}

	if (session->action == ACTION_RETWEET) {
		if (!session->retweet) {
			char *rtid;

			fprintf(stdout, "Status ID to retweet: ");
			rtid = get_string_from_stdin();
			session->retweet = zalloc(strlen(rtid) + 10);
			sprintf(session->retweet, "%s", rtid);
			free(rtid);
		}

		if (!session->retweet || strlen(session->retweet) == 0) {
			dbg("no retweet?\n");
			return -1;
		}

		dbg("retweet ID = %s\n", session->retweet);
	}

	if (session->action == ACTION_UPDATE) {
		if (session->background || !session->interactive)
			tweet = get_string_from_stdin();
		else
			tweet = session->readline("tweet: ");
		if (!tweet || strlen(tweet) == 0) {
			dbg("no tweet?\n");
			return -1;
		}

		if (session->shrink_urls)
			tweet = shrink_urls(tweet);

		session->tweet = zalloc(strlen(tweet) + 10);
		if (session->bash)
			sprintf(session->tweet, "%c %s",
				getuid() ? '$' : '#', tweet);
		else
			sprintf(session->tweet, "%s", tweet);

		free(tweet);
		dbg("tweet = %s\n", session->tweet);
	}

	if (session->page == 0)
		session->page = 1;
	dbg("config file = %s\n", session->configfile);
	dbg("host = %d\n", session->host);
	dbg("action = %d\n", session->action);

	/* fork ourself so that the main shell can get on
	 * with it's life as we try to connect and handle everything
	 */
	if (session->background) {
		child = fork();
		if (child) {
			dbg("child is %d\n", child);
			exit(0);
		}
	}

	retval = send_request(session);
	if (retval && !session->background)
		fprintf(stderr, "operation failed\n");

	log_session(session, retval);
exit:
	session_readline_cleanup(session);
	session_free(session);
	return retval;;
}
예제 #6
0
/**
 * Main daemon routine
 */
int main( int argc, char **argv )
{
    int            c, i, option_index = 0;
    char          *bin = basename( argv[0] );

    int            rc;
    char           err_msg[4096];
    robinhood_config_t rh_config;
    int chgd = 0;
    char           badcfg[RBH_PATH_MAX];
    char           tag_name[256] = "";

    start_time = time( NULL );

    zero_options( &options );

    /* parse command line options */
    while ( ( c = getopt_long( argc, argv, SHORT_OPT_STRING, option_tab, &option_index ) ) != -1 )
    {
        switch ( c )
        {
        case 's':
            options.partial_scan = TRUE;
            strncpy(options.partial_scan_path, optarg, RBH_PATH_MAX);
            /* clean final slash */
            if (FINAL_SLASH(options.partial_scan_path))
                REMOVE_FINAL_SLASH(options.partial_scan_path);
            break;

        case 'd':
            if (parse_diff_mask(optarg, &options.diff_mask, err_msg))
            {
                fprintf(stderr,
                        "Invalid argument for --diff: %s\n", err_msg);
                exit( 1 );
            }
            break;

        case 'a':
            if (optarg)
            {
                if (!strcasecmp(optarg,"fs"))
                    options.diff_arg.apply = APPLY_FS;
                else if (!strcasecmp(optarg,"db"))
                    options.diff_arg.apply = APPLY_DB;
                else
                {
                    fprintf(stderr, "Invalid argument for --apply: '%s' (fs or db expected)\n",
                            optarg);
                    exit( 1 );
                }
            }
            else
                options.diff_arg.apply = APPLY_DB;
            break;

        case 'D':
                options.flags |= FLAG_DRY_RUN;
            break;

        case 'f':
            strncpy( options.config_file, optarg, MAX_OPT_LEN );
            break;
#ifdef _HSM_LITE
        case 'b':
            options.diff_arg.recov_from_backend  = 1;
            break;
#endif
#ifdef _HAVE_FID /* only for lustre 2.x */
        case 'o':
            strncpy(options.output_dir, optarg, MAX_OPT_LEN);
            break;
#endif
        case 'l':
            options.force_log_level = TRUE;
            options.log_level = str2debuglevel( optarg );
            if ( options.log_level == -1 )
            {
                fprintf( stderr,
                         "Unsupported log level '%s'. CRIT, MAJOR, EVENT, VERB, DEBUG or FULL expected.\n",
                         optarg );
                exit( 1 );
            }
            break;
        case 'h':
            display_help( bin );
            exit( 0 );
            break;
        case 'V':
            display_version( bin );
            exit( 0 );
            break;
        case ':':
        case '?':
        default:
            fprintf(stderr,"Run '%s --help' for more details.\n", bin);
            exit( 1 );
            break;
        }
    }

    /* check there is no extra arguments */
    if ( optind != argc )
    {
        fprintf( stderr, "Error: unexpected argument on command line: %s\n", argv[optind] );
        exit( 1 );
    }

    /* Initialize global tools */
#ifdef _LUSTRE
    if ( ( rc = Lustre_Init(  ) ) )
    {
        fprintf( stderr, "Error %d initializing liblustreapi\n", rc );
        exit( 1 );
    }
#endif

    /* Initilize uidgid cache */
    if ( InitUidGid_Cache(  ) )
    {
        fprintf( stderr, "Error initializing uid/gid cache\n" );
        exit( 1 );
    }

    /* get default config file, if not specified */
    if ( SearchConfig( options.config_file, options.config_file, &chgd, badcfg ) != 0 )
    {
        fprintf(stderr, "No config file (or too many) found matching %s\n", badcfg);
        exit(2);
    }
    else if (chgd)
    {
        fprintf(stderr, "Using config file '%s'.\n", options.config_file );
    }

    if ( ReadRobinhoodConfig( MODULE_MASK_FS_SCAN | MODULE_MASK_ENTRY_PROCESSOR,
                              options.config_file, err_msg,
                              &rh_config, FALSE ) )
    {
        fprintf( stderr, "Error reading configuration file '%s': %s\n",
                 options.config_file, err_msg );
        exit( 1 );
    }
    process_config_file = options.config_file;

    /* set global configuration */
    global_config = rh_config.global_config;

    /* set policies info */
    policies = rh_config.policies;

    if (options.force_log_level)
        rh_config.log_config.debug_level = options.log_level;
    else
        rh_config.log_config.debug_level = LVL_CRIT; /* no event message */

    /* Set logging to stderr */
    strcpy( rh_config.log_config.log_file, "stderr" );
    strcpy( rh_config.log_config.report_file, "stderr" );
    strcpy( rh_config.log_config.alert_file, "stderr" );

    /* Initialize logging */
    rc = InitializeLogs( bin, &rh_config.log_config );
    if ( rc )
    {
        fprintf( stderr, "Error opening log files: rc=%d, errno=%d: %s\n",
                 rc, errno, strerror( errno ) );
        exit( rc );
    }

    /* Initialize filesystem access */
    rc = InitFS();
    if (rc)
        exit(rc);

#ifdef _HSM_LITE
    rc = Backend_Start( &rh_config.backend_config, options.flags );
    if ( rc )
    {
        DisplayLog( LVL_CRIT, DIFF_TAG, "Error initializing backend" );
        exit( 1 );
    }
#endif

    /* Initialize list manager */
    rc = ListMgr_Init( &rh_config.lmgr_config, FALSE );
    if ( rc )
    {
        DisplayLog( LVL_CRIT, DIFF_TAG, "Error %d initializing list manager", rc );
        exit( rc );
    }
    else
        DisplayLog( LVL_VERB, DIFF_TAG, "ListManager successfully initialized" );


    if ( CheckLastFS(  ) != 0 )
        exit( 1 );

    if (options.diff_mask)
        rh_config.entry_proc_config.diff_mask = options.diff_mask;
    else
    {
        /* parse "all" */
        char tmpstr[] = "all";
        if (parse_diff_mask(tmpstr, &rh_config.entry_proc_config.diff_mask, err_msg))
        {
            DisplayLog(LVL_CRIT, DIFF_TAG, "unexpected error parsing diff mask: %s", err_msg);
            exit(1);
        }
    }

#ifdef LUSTRE_DUMP_FILES
    if (options.diff_arg.apply == APPLY_FS && !(options.flags & FLAG_DRY_RUN))
    {
        /* open the file to write LOV EA and FID remapping */
        if (!EMPTY_STRING(options.output_dir))
        {
            char fname[RBH_PATH_MAX];
            if (mkdir(options.output_dir, 0700) && (errno != EEXIST))
            {
                DisplayLog(LVL_CRIT, DIFF_TAG, "Failed to create directory %s: %s",
                           options.output_dir, strerror(errno));
                exit(1);
            }
            snprintf(fname, RBH_PATH_MAX-1, "%s/"LOVEA_FNAME, options.output_dir);
            options.diff_arg.lovea_file = fopen(fname, "w");
            if (options.diff_arg.lovea_file == NULL)
            {
                DisplayLog(LVL_CRIT, DIFF_TAG, "Failed to open %s for writting: %s",
                           fname, strerror(errno));
                exit(1);
            }
            snprintf(fname, RBH_PATH_MAX-1, "%s/"FIDREMAP_FNAME, options.output_dir);
            options.diff_arg.fid_remap_file = fopen(fname, "w");
            if (options.diff_arg.fid_remap_file == NULL)
            {
                DisplayLog(LVL_CRIT, DIFF_TAG, "Failed to open %s for writting: %s",
                           fname, strerror(errno));
                exit(1);
            }
        }
    }
#endif

    /* if no DB apply action is specified, can't use md_update field for checking
     * removed entries. So, create a special tag for that. */
    if ((options.diff_arg.apply != APPLY_DB) || (options.flags & FLAG_DRY_RUN))
    {
        fprintf(stderr, "Preparing diff table...\n");

        /* create a connexion to the DB. this is safe to use the global lmgr var
         * as statistics thread is not running */
        if (!ensure_db_access())
            exit(1);
        /* create a tag to clear entries after the scan */

        /* There could be several diff running in parallel,
         * so set a suffix to avoid conflicts */
        sprintf(tag_name, "DIFF_%u", (unsigned int) getpid());
        options.diff_arg.db_tag = tag_name;

        /* add filter for partial scan */
        if (options.partial_scan)
        {
            lmgr_filter_t  filter;
            filter_value_t val;
            lmgr_simple_filter_init( &filter );

            char tmp[RBH_PATH_MAX];
            strcpy(tmp, options.partial_scan_path);
            strcat(tmp, "/*");
            val.value.val_str = tmp;
            lmgr_simple_filter_add(&filter, ATTR_INDEX_fullpath, LIKE, val, 0);

            rc = ListMgr_CreateTag(&lmgr, tag_name, &filter, FALSE);
            lmgr_simple_filter_free(&filter);
        }
        else
            rc = ListMgr_CreateTag(&lmgr, tag_name, NULL, FALSE);

        if (rc)
            exit(rc);
    }

    /* Initialise Pipeline */
    rc = EntryProcessor_Init(&rh_config.entry_proc_config, DIFF_PIPELINE,
                             options.flags, &options.diff_arg);
    if ( rc )
    {
        DisplayLog( LVL_CRIT, DIFF_TAG, "Error %d initializing EntryProcessor pipeline", rc );
        goto clean_tag;
    }
    else
        DisplayLog( LVL_VERB, DIFF_TAG, "EntryProcessor successfully initialized" );

    fprintf(stderr, "Starting scan\n");

    /* print header to indicate the content of diff
     * #<diff cmd>
     * ---fs[=/subdir]
     * +++db
     */
    for (i = 0; i < argc; i++)
        printf("%s%s", i==0?"# ":" ", argv[i]);
    printf("\n");
    if (options.diff_arg.apply == APPLY_FS)
    {
        if (options.partial_scan)
            printf("---fs=%s\n",options.partial_scan_path);
        else
            printf("---fs\n");
        printf("+++db\n");
    }
    else
    {
        printf("---db\n");
        if (options.partial_scan)
            printf("+++fs=%s\n",options.partial_scan_path);
        else
            printf("+++fs\n");
    }

    /* Start FS scan */
    if (options.partial_scan)
        rc = FSScan_Start(&rh_config.fs_scan_config, options.flags,
                          options.partial_scan_path);
    else
        rc = FSScan_Start(&rh_config.fs_scan_config, options.flags, NULL);

    if ( rc )
    {
        DisplayLog( LVL_CRIT, DIFF_TAG, "Error %d initializing FS Scan module", rc );
        goto clean_tag;
    }
    else
        DisplayLog( LVL_VERB, DIFF_TAG, "FS Scan module successfully initialized" );

    /* Flush logs now, to have a trace in the logs */
    FlushLogs(  );

    /* both pipeline and scan are now running, can now trap events and display stats */

    /* create signal handling thread */
    rc = pthread_create( &sig_thr, NULL, signal_handler_thr, NULL );
    if ( rc )
    {
        DisplayLog( LVL_CRIT, DIFF_TAG, "Error starting signal handler thread: %s",
                    strerror( errno ) );
        goto clean_tag;
    }
    else
        DisplayLog( LVL_VERB, DIFF_TAG, "Signal handler thread started successfully" );

    pthread_create(&stat_thread, NULL, stats_thr, NULL);

    /* wait for FS scan to end */
    FSScan_Wait(  );
    DisplayLog( LVL_MAJOR, DIFF_TAG, "FS Scan finished" );

    /* Pipeline must be flushed */
    EntryProcessor_Terminate( TRUE );

#ifdef LUSTRE_DUMP_FILES
    /* flush the lovea file */
    if (options.diff_arg.lovea_file)
    {
        fprintf(stderr, " > LOV EA information written to %s/"LOVEA_FNAME"\n", options.output_dir);
        fclose(options.diff_arg.lovea_file);
    }
    if (options.diff_arg.fid_remap_file)
    {
        fprintf(stderr, " > FID remapping written to %s/"FIDREMAP_FNAME"\n", options.output_dir);
        fclose(options.diff_arg.fid_remap_file);
    }
#endif

    fprintf(stderr, "End of scan\n");

    DisplayLog( LVL_MAJOR, DIFF_TAG, "All tasks done! Exiting." );
    rc = 0;

clean_tag:
    /* destroy the tag before exit */
    if (options.diff_arg.db_tag != NULL && ensure_db_access())
    {
        fprintf(stderr, "Cleaning diff table...\n");
        ListMgr_DestroyTag(&lmgr, options.diff_arg.db_tag);
    }

    exit(rc);
    return rc; /* for compiler */
}
void process_options(int argc, char *argv[])
{
	int error = 0, option_index;
	static const struct option long_options[] = {
		{"output", required_argument, 0, 800},
		{"name", required_argument, 0, 1000},
		{"major", required_argument, 0, 2000},
		{"minor", required_argument, 0, 2500},
		{"reserved_blocks", required_argument, 0, 3000},
		{"start_blkind", required_argument, 0, 3500},
		{"num_blocks", required_argument, 0, 4000},
		{"data_type", required_argument, 0, 4500},
		{0, 0, 0, 0},
	};

	for (;;) {
		int option_index = 0;

		int c = getopt_long(argc, argv, "", long_options, &option_index);
		if (c == -1)
			break;

		switch (c) {
			case 'q':
				quiet = 1;
				break;
			case 800:
				out = optarg;
				break;
			case 1000:
				name = optarg;
				break;
			case 2000:
				version.major_version = strtol(optarg, NULL, 0);
				break;
			case 2500:
				version.minor_version = strtol(optarg, NULL, 0);
				break;
			case 3000:
				reserved_blocks = strtol(optarg, NULL, 0);
				break;
			case 3500:
				chip_start_blkind = strtol(optarg, NULL, 0);
				break;
			case 4000:
				chip_num_blocks = strtol(optarg, NULL, 0);
				break;
			case 4500:
				if (!strncmp(optarg, "oob", 3))
					data_type = DATA_TYPE_OOB;
				else if (!strncmp(optarg, "raw", 3))
					data_type = DATA_TYPE_RAW;
				else if (!strncmp(optarg, "normal", 6))
					data_type = DATA_TYPE_NORMAL;
				else {
					printf("Not support data type. Using default normal\n");
					//return;
				}

				break;
			case 'h':
				display_help();
				exit(0);
				break;
			case '?':
				error = 1;
				break;
		}
	}

	if ( !name || !out || version.major_version==-1 || version.minor_version==-1 ||
			reserved_blocks==-1 || chip_start_blkind==-1 || chip_num_blocks==-1 ||
			(argc - optind) < 1 || error) {
		display_help();
		exit(1);
	}

	in = argv[optind];
}
예제 #8
0
int 
main(int argc, char *argv[])
{
  int            x; 
  int            result;
  DATA           D = new_data();
  CREW           crew;           /* thread pool - crew.h */
  LINES          *lines;         /* defined in setup.h   */
  CLIENT         *client;        /* defined in setup.h   */
  URL            **urls;         /* urls struct array    */
  pthread_t      cease;          /* the shutdown thread  */
  pthread_t      timer;          /* the timer thread     */
  pthread_attr_t scope_attr;     /* set to PTHREAD_SCOPE_SYSTEM */
  unsigned int   randrseed;      /* seed pthread_rand_np */
  char           exlogmsg[512];
  void *statusp;
  sigset_t sigs;

  sigemptyset(&sigs);
  sigaddset(&sigs, SIGHUP);
  sigaddset(&sigs, SIGINT);
  sigaddset(&sigs, SIGALRM);
  sigaddset(&sigs, SIGTERM);
  sigprocmask(SIG_BLOCK, &sigs, NULL);

  lines = xcalloc(sizeof(LINES),1);
  lines->index   = 0;
  lines->line    = NULL;

  memset(&my, 0, sizeof(struct CONFIG));

  parse_rc_cmdline(argc, argv); 
  if(init_config() < 0){        /* defined in init.h   */
    exit( EXIT_FAILURE );       /* polly was a girl... */
  } 
  parse_cmdline(argc, argv);    /* defined above       */
  ds_module_check();            /* check config integ  */

  if(my.get){
    my.cusers  = 1;
    my.reps    = 1;
    my.logging = FALSE;
    my.bench   = TRUE;
  } 

  if(my.config){
    show_config(TRUE);    
  }

  if(my.url != NULL){
    my.length = 1; 
  } else { 
    my.length = read_cfg_file( lines, my.file ); 
  }

  if(my.length == 0){ 
    display_help();
  }

  /* cookie is an EXTERN, defined in setup */ 
  cookie = xcalloc(sizeof(COOKIE), 1); 
  cookie->first = NULL;
  if((result = pthread_mutex_init( &(cookie->mutex), NULL)) !=0){
    joe_fatal( "pthread_mutex_init" );
  } 

  /* memory allocation for threads and clients */
  urls   = xmalloc(my.length * sizeof(URL));
  client = xmalloc(sizeof(CLIENT) * my.cusers);
  if((crew = new_crew(my.cusers, my.cusers, FALSE)) == NULL){
    joe_fatal("unable to allocate memory for %d simulated browser", my.cusers);  
  }

  /** 
   * determine the source of the url(s),
   * command line or file, and add them
   * to the urls struct.
   */
  if(my.url != NULL){
    urls[0]   =  add_url(my.url, 1);         /* from command line  */
  } else { 
    for(x = 0; x < my.length; x ++){
      urls[x] =  add_url(lines->line[x], x); /* from urls.txt file */
    }
  } 

  /**
   * display information about the siege
   * to the user and prepare for verbose 
   * output if necessary.
   */
  if(!my.get){
    fprintf(stderr, "** "); 
    display_version(FALSE);
    fprintf(stderr, "** Preparing %d concurrent users for battle.\n", my.cusers);
    fprintf(stderr, "The server is now under siege...");
    if(my.verbose){ fprintf(stderr, "\n"); }
	if(my.extralog) { 
		snprintf(exlogmsg, sizeof exlogmsg, "** Preparing %d concurrent users for battle.", my.cusers);
		log_extra(exlogmsg);
		log_extra("The server is now under siege...");
	}
  }

  /**
   * record start time before spawning threads
   * as the threads begin hitting the server as
   * soon as they are created.
   */
  data_set_start(D);

  /**
   * for each concurrent user, spawn a thread and
   * loop until condition or pthread_cancel from the
   * handler thread.
   */
  pthread_attr_init(&scope_attr);
  pthread_attr_setscope(&scope_attr, PTHREAD_SCOPE_SYSTEM);
#if defined(_AIX)
  /* AIX, for whatever reason, defies the pthreads standard and  *
   * creates threads detached by default. (see pthread.h on AIX) */
  pthread_attr_setdetachstate(&scope_attr, PTHREAD_CREATE_JOINABLE);
#endif

  /** 
   * invoke OpenSSL's thread safety
   */
#ifdef HAVE_SSL
  SSL_thread_setup();
#endif

  /**
   * create the signal handler and timer;  the
   * signal handler thread (cease) responds to
   * ctrl-C (sigterm) and the timer thread sends
   * sigterm to cease on time out.
   */
  if((result = pthread_create(&cease, NULL, (void*)sig_handler, (void*)crew)) < 0){
    joe_fatal("failed to create handler: %d\n", result);
  }
  if(my.secs > 0){
    if((result = pthread_create(&timer, NULL, (void*)siege_timer, (void*)cease)) < 0){
      joe_fatal("failed to create handler: %d\n", result);
    } 
  }
  
  randrseed = time(0);

  /**
   * loop until my.cusers and create a corresponding thread...
   */  
  for(x = 0; x < my.cusers && crew_get_shutdown(crew) != TRUE; x++){
    client[x].id              = x; 
    client[x].bytes           = 0;
    client[x].time            = 0.0;
    client[x].hits            = 0;
    client[x].code            = 0;
    client[x].ok200           = 0;   
    client[x].fail            = 0; 
    client[x].U               = urls;
    client[x].auth.www        = 0;
    client[x].auth.proxy      = 0;
    client[x].auth.type.www   = BASIC;
    client[x].auth.type.proxy = BASIC;
    client[x].rand_r_SEED     = pthread_rand_np(&randrseed);
    result = crew_add(crew, (void*)start_routine, &(client[x]));
    if(result == FALSE){ 
      my.verbose = FALSE;
      fprintf(stderr, "Unable to spawn additional threads; you may need to\n");
      fprintf(stderr, "upgrade your libraries or tune your system in order\n"); 
      fprintf(stderr, "to exceed %d users.\n", my.cusers);
      joe_fatal("system resources exhausted"); 
    }
  } /* end of for pthread_create */

  crew_join(crew, TRUE, &statusp);

#ifdef HAVE_SSL
  SSL_thread_cleanup();
#endif

  /**
   * collect all the data from all the threads that
   * were spawned by the run.
   */
  for(x = 0; x < ((crew_get_total(crew) > my.cusers || 
                   crew_get_total(crew)==0 ) ? my.cusers : crew_get_total(crew)); x++){
    data_increment_count(D, client[x].hits);
    data_increment_bytes(D, client[x].bytes);
    data_increment_total(D, client[x].time);
    data_increment_code (D, client[x].code);
    data_increment_ok200(D, client[x].ok200);
    data_increment_fail (D, client[x].fail);
    data_set_highest    (D, client[x].bigtime);
    data_set_lowest     (D, client[x].smalltime);
    client[x].rand_r_SEED = pthread_rand_np(&randrseed);
  } /* end of stats accumulation */
  
  /**
   * record stop time
   */
  data_set_stop(D);

  /**
   * cleanup crew
   */ 
  crew_destroy(crew);

  if(my.get){
    if(data_get_count(D) > 0){
      exit(EXIT_SUCCESS);
    } else {
      printf("[done]\n");
      exit(EXIT_FAILURE);
    }
  }

  /**
   * take a short nap  for  cosmetic  effect
   * this does NOT affect performance stats.
   */
  pthread_usleep_np(10000);
  if(my.verbose)
    fprintf(stderr, "done.\n");
  else
    fprintf(stderr, "\b      done.\n");
  if(my.extralog)
	log_extra("done.");

  /**
   * prepare and print statistics.
   */
  if(my.failures > 0 && my.failed >= my.failures){
    fprintf(stderr, "%s aborted due to excessive socket failure; you\n", program_name);
    fprintf(stderr, "can change the failure threshold in $HOME/.%src\n", program_name);
  }
  fprintf(stderr, "\bTransactions:\t\t%12u hits\n",        data_get_count(D));
  fprintf(stderr, "Availability:\t\t%12.2f %%\n",          data_get_count(D)==0 ? 0 :
                                                           (double)data_get_count(D) /
                                                           (data_get_count(D)+my.failed)
                                                           *100
  );
  fprintf(stderr, "Elapsed time:\t\t%12.2f secs\n",        data_get_elapsed(D));
  fprintf(stderr, "Data transferred:\t%12.2f MB\n",        data_get_megabytes(D)); /*%12llu*/
  fprintf(stderr, "Response time:\t\t%12.2f secs\n",       data_get_response_time(D));
  fprintf(stderr, "Transaction rate:\t%12.2f trans/sec\n", data_get_transaction_rate(D));
  fprintf(stderr, "Throughput:\t\t%12.2f MB/sec\n",        data_get_throughput(D));
  fprintf(stderr, "Concurrency:\t\t%12.2f\n",              data_get_concurrency(D));
  fprintf(stderr, "Successful transactions:%12u\n",        data_get_code(D)); 
  if(my.debug){
    fprintf(stderr, "HTTP OK received:\t%12u\n",             data_get_ok200(D));
  }
  fprintf(stderr, "Failed transactions:\t%12u\n",          my.failed);
  fprintf(stderr, "Longest transaction:\t%12.2f\n",        data_get_highest(D));
  fprintf(stderr, "Shortest transaction:\t%12.2f\n",       data_get_lowest(D));
  fprintf(stderr, " \n");
  if(my.mark)    mark_log_file(my.markstr);
  if(my.logging) log_transaction(D);

  data_destroy(D);
  if(my.url == NULL){
    for(x = 0; x < my.length; x++)
       xfree(lines->line[x]);
    xfree(lines->line);
    xfree(lines);
  }  

  exit(EXIT_SUCCESS);	
} /* end of int main **/
예제 #9
0
파일: btcmd.c 프로젝트: luongli/Cprograming
int btcmd_help(CMDBLK* c)
{
    display_help(current_app_cmds,c->arg);
    return 0;
}
예제 #10
0
static void process_options(int argc, char * const argv[])
{
	int error = 0;

	for (;;) {
		int option_index = 0;
		static const char short_options[] = "hV";
		static const struct option long_options[] = {
			{"version", no_argument, 0, 'V'},
			{"help", no_argument, 0, 'h'},
			{0, 0, 0, 0},
		};

		int c = getopt_long(argc, argv, short_options,
				long_options, &option_index);
		if (c == EOF) {
			break;
		}

		switch (c) {
			case 'V':
				display_version();
				break;
			case 'h':
				display_help(EXIT_SUCCESS);
				break;
			case '?':
				error++;
				break;
		}
	}

	if ((argc - optind) < 3 || error)
		display_help(EXIT_FAILURE);

	const char *s_command = argv[optind++];
	mtddev = argv[optind++];

	if (strcmp(s_command, "del") == 0 && (argc - optind) == 1) {
		const char *s_part_no = argv[optind++];

		long tmp = simple_strtol(s_part_no, &error);
		if (tmp < 0)
		       errmsg_die("Can't specify negative partition number: %ld",
				  tmp);
		if (tmp > INT_MAX)
		       errmsg_die("Partition number exceeds INT_MAX: %ld",
				  tmp);

		part_no = tmp;
		command = COMMAND_DEL;
	} else if (strcmp(s_command, "add") == 0 && (argc - optind) == 3) {
		const char *s_start;
		const char *s_length;

		part_name = argv[optind++];
		s_start = argv[optind++];
		s_length = argv[optind++];

		if (strlen(part_name) >= BLKPG_DEVNAMELTH)
			errmsg_die("Partition name (%s) should be less than %d characters",
				   part_name, BLKPG_DEVNAMELTH);

		start_addr = simple_strtoll(s_start, &error);
		if (start_addr < 0)
		       errmsg_die("Can't specify negative start offset: %lld",
				  start_addr);

		length = simple_strtoll(s_length, &error);
		if (length < 0)
		       errmsg_die("Can't specify negative length: %lld",
				  length);

		command = COMMAND_ADD;
	} else
		display_help(EXIT_FAILURE);

	if (error)
		display_help(EXIT_FAILURE);
}
예제 #11
0
/**
 * parses command line arguments and assigns
 * values to run time variables. relies on GNU
 * getopts included with this distribution.  
 */ 
void 
parse_cmdline(int argc, char *argv[])
{
  int c = 0;
  int nargs;
  while((c = getopt_long( argc, argv, "VhvCDglibr:t:f:d:c:u:m:H:R:A:E:", 
          long_options, (int *)0)) != EOF){
  switch(c){
      case 'V':
        display_version(TRUE);
        break;
      case 'h':
        display_help();
        exit(EXIT_SUCCESS);
      case 'D':
        my.debug = TRUE;
        break;
      case 'C':
        my.config = TRUE;
        break;
      case 'c':
        my.cusers  = atoi(optarg);
        break;
      case 'i':
        my.internet = TRUE;
        break;
      case 'b':
        my.bench    = TRUE;
        break;
      case 'd':
	/* XXX range checking? use strtol? */
        my.delay   = atoi(optarg);
	if(my.delay < 0){
	  my.delay = 0; 
	}
        break;
      case 'g':
        my.get = TRUE;
        break;
      case 'l':
        my.logging = TRUE;
        break;
      case 'm':
        my.mark    = TRUE;
        my.markstr = optarg;
        my.logging = TRUE; 
        break;
      case 'v':
        my.verbose = TRUE;
        break;
      case 'r':
        my.reps = atoi(optarg);
        break;
      case 't':
        parse_time(optarg);
        break;
      case 'f':
        memset(my.file, 0, sizeof(my.file));
        if(optarg == NULL) break; /*paranoia*/
        strncpy(my.file, optarg, strlen(optarg));
        break;
      case 'u':
        printf("-u has been deprecated.\n");
        display_help(); 
        exit(1);
        break;
      case 'A':
        strncpy(my.uagent, optarg, 255);
        break;
      case 'R':  
        /**
         * processed above 
         */
        break; 
      case 'H':
        {
          if(!strchr(optarg,':')) joe_fatal("no ':' in http-header");
          if((strlen(optarg) + strlen(my.extra) + 3) > 512)
              joe_fatal("too many headers");
          strcat(my.extra,optarg);
          strcat(my.extra,"\015\012");
        }
        break;
      case 'E':
	    my.extralog = TRUE;
		memset(my.exfile, 0, sizeof(my.exfile));
        if(optarg == NULL) break; /*paranoia*/
        strncpy(my.exfile, optarg, strlen(optarg));
		break;
    } /* end of switch( c )           */
  }   /* end of while c = getopt_long */
  nargs = argc - optind;
  if(nargs)
    my.url = xstrdup(argv[argc-1]); 
  if(my.get && my.url==NULL){
    puts("ERROR: -g/--get requires a commandline URL");
    exit(1);
  }
  return;
} /* end of parse_cmdline */
예제 #12
0
void parse_options (int actual_argc, char *actual_argv[])
{
  int op;
  static int n_from_args;
  argc = actual_argc; argv = actual_argv;

  while ((op = getopt(argc, argv, sand_optstring)) != -1) {
    switch (op) {
    case 'h':
      display_help_opt = true;
      break;
    case 'v':
      display_version_opt = true;
      break;
    case 'u':
      underground_opt = true;
      break;
    case 'g':
      graphical_opt = true;
      break;
    case 'i':
      printf ("option -i not yet implemented\n");
      interactive_opt = true;
      break;
    case 'j':
      if (strcmp(optarg, "time") == 0) {
	selected_job = TIME_JOB;
      } else if (strcmp(optarg, "area") == 0) {
	selected_job = AREA_JOB;
      } else {
	cantcontinue ("Option \"-j %s\" not understood.\n", optarg);
      }
      break;
    case 'o': /* expects path for output file */
      printf ("option -o not yet implemented\n");
      //parse_ofile_arg (optarg);
      break;
    case 'f': /* expects path for snapshot file */
      snapshot_source_file_arg = optarg;
      from_snapshot_mode = true;
      break;
    case 's': /* expects numerical value for n */
      if (sscanf (optarg, "%d", &n_from_args) != 1) {/*FIXME: prefer strtol*/
	fprintf (stderr, "ERROR: %s: \"-s %s\" is not an integer argument.\n", __func__, optarg);
	fail ();
      } else if ((n_from_args < 0) || (n_from_args > MAX_ALLOWED_SNAPSHOT_DELAY)) {
	fprintf (stderr, "ERROR: %s: \"-s %d\" is out of valid range 0..%d.\n", __func__, n_from_args, MAX_ALLOWED_SNAPSHOT_DELAY);
	fail ();
      }
      set_value_for_snapshot_delay (n_from_args);
      break;
    case 't': /* expects numerical value for n */
      if (sscanf (optarg, "%d", &n_from_args) != 1) {/*FIXME: prefer strtol*/
	fprintf (stderr, "ERROR: %s: \"-t %s\" is not an integer argument.\n", __func__, optarg);
	fail ();
      } else if ((n_from_args < 0) || (n_from_args > MAX_ALLOWED_ANIM_LEVEL)) {
	fprintf (stderr, "ERROR: %s: \"-t %d\" is out of valid range 0..%d.\n", __func__, n_from_args, MAX_ALLOWED_ANIM_LEVEL);
	fail ();
      }
      set_value_for_anim_level (n_from_args);
      break;
    case 'n': /* expects numerical value for n */
      if (sscanf (optarg, "%d", &n_from_args) != 1) {/*FIXME: prefer strtol*/
	fprintf (stderr, "ERROR: %s: \"-n %s\" is not an integer argument.\n", __func__, optarg);
	fail ();
      } else if  ((n_from_args < 0) || (n_from_args > MAX_ALLOWED_HEIGHT)) {
	fprintf (stderr, "ERROR: %s: \"-n %d\" is out of valid range 0..%d.\n", __func__, n_from_args, MAX_ALLOWED_HEIGHT);
	fail ();
      }
      set_value_for_height (n_from_args);
      break;
    case 'd': /* expects numerical value for d */
      if (sscanf (optarg, "%d", &n_from_args) != 1) {/*FIXME: prefer strtol*/
	fprintf (stderr, "ERROR: %s: \"-d %s\" is not an integer argument.\n", __func__, optarg);
	fail ();
      } else if  ((n_from_args < 0) || (n_from_args > MAX_ALLOWED_DIM)) {
	fprintf (stderr, "ERROR: %s: \"-d %d\" is out of valid range 0..%d.\n", __func__, n_from_args, MAX_ALLOWED_DIM);
	fail ();
      }
      set_value_for_max_dim (n_from_args);
      break;
    case '?':
    default:
      fprintf (stderr, "ERROR: %s: Cannot parse optional args\n", __func__);
      display_help (stderr);
      fail ();
    }
  }
  if (argc > optind) {
    fprintf (stderr, "ERROR: %s: Does not know about arg \"%s\"\n",
	     __func__, argv[optind]);
    fail();
  }
}
예제 #13
0
파일: vsub.c 프로젝트: vchandnani/vsub-c
int main()
{
	void display_help();
	void get_strings();
  char *search_strings();
	void copy_strings();
	void display_results();

	char str1[32], str2[4], str3[8], str4[1024];
  char *ptr1, *ptr2, *ptr3;
	char *start_ptr, *match_ptr, *copy_ptr;
	int match_ctr;

	ptr1 = ptr2 = ptr3 = NULL;
	start_ptr = match_ptr = copy_ptr = NULL;
	match_ctr = 0;

  display_help();
  get_strings( str1, str2, str3 );

	ptr1 = str1;
	ptr2 = str2;
	ptr3 = str3;

	start_ptr = str1;
	copy_ptr = str4;

//	TO DO: while( *start_ptr != '\0' )
	while( start_ptr <= ( str1 + strlen( str1 ) ) ) 
	{
if( debug_flag == 1 )
printf( "\n START ptr = %c", *start_ptr );
  	match_ptr = search_strings( str1, str2, start_ptr );
		if( match_ptr )
		{ 
			match_ctr ++;
if( debug_flag == 1 )
printf( "\n if - MATCH ctr %d: need to start copy/replace", match_ctr );
			// RESULT STRING: copy from archive string start location to match location
			copy_strings( start_ptr, match_ptr, str4, copy_ptr );
			copy_ptr += match_ptr - start_ptr;
			// RESULT STRING: copy entire replacement string, i.e. replace query string
			copy_strings( ptr3, ptr3 + strlen( str3 ), str4, copy_ptr );
if( debug_flag == 1 )
printf( "\n MATCH: RESULT STR4: %s", str4 );
			start_ptr = match_ptr + strlen(str2);
			copy_ptr += strlen( str3 );
if( debug_flag == 1 )
printf( "\n continue searching from %c", *start_ptr );
		}
		else
		{
if( debug_flag == 1 )
printf("\n else - match ctr = %d", match_ctr);
			if( match_ctr != 0)
			{
				// RESULT STRING: copy from archive string last match location until end
if( debug_flag == 1 )
printf( "\n NO MATCH: copy from last match start ptr %c until end", *start_ptr );
				copy_strings( start_ptr, str1 + strlen( str1 ), str4, copy_ptr );
if( debug_flag == 1 )
printf( "\n NO MATCH: RESULT STR4: %s", str4 );
				break;
			}
			else
			{
				strcpy( str4, "The archive string does not contain the query string." );
				break;
			}
			start_ptr ++;
		}
	}

	display_results( str1, str2, str3, str4 );
	return 0;
} // end main()
int main(int argc, char** argv) {
  int argn_dec;
  OMX_ERRORTYPE err;
  OMX_INDEXTYPE eIndexParamFilename;
  int gain=-1;
  OMX_AUDIO_CONFIG_VOLUMETYPE sVolume;
  OMX_TIME_CONFIG_TIMESTAMPTYPE sTimeStamp;
  OMX_PARAM_COMPONENTROLETYPE sComponentRole;
  
  char *stream_dir=NULL;
  DIR *dirp;
	struct dirent *dp;
  int seek=1;

  flagSetupTunnel = 1;
  flagPlaybackOn = 1;
  flagUsingFFMpeg = 1;
  flagIsGain = 0;

  if(argc <= 3) {
    argn_dec = 1;
    while (argn_dec<argc) {
      if (*(argv[argn_dec]) =='-') {
        switch (*(argv[argn_dec]+1)) {
        case 's':
          seek = 0;
          break;
        //case 't':
        //  flagSetupTunnel = 0;
        //  break;
        default:
          display_help();
        }
      } else {
        stream_dir = malloc(strlen(argv[argn_dec]) * sizeof(char) + 1);
        strcpy(stream_dir,argv[argn_dec]);
      }
      argn_dec++;
    }
  } else if(argc > 3) {
    display_help();
  }

  if(stream_dir==NULL) {

    stream_dir = malloc(strlen(getenv("HOME")) * sizeof(char) + 20);
    memset(stream_dir, 0, sizeof(stream_dir));
	  strcat(stream_dir, getenv("HOME"));
	  strcat(stream_dir, "/stream/audio/");
  }

  DEBUG(DEFAULT_MESSAGES, "Directory Name=%s\n",stream_dir);

  /* Populate the registry file */
	dirp = opendir(stream_dir);
	if(dirp == NULL){
    int err = errno;
		DEBUG(DEB_LEV_ERR, "Cannot open directory %s\n", stream_dir);
		return err;
	}

  
  /** initializing appPriv structure */
  appPriv = malloc(sizeof(appPrivateType));
  appPriv->filereaderEventSem = malloc(sizeof(tsem_t));
  appPriv->decoderEventSem = malloc(sizeof(tsem_t));
  appPriv->eofSem = malloc(sizeof(tsem_t));
  if (flagPlaybackOn) {
    appPriv->sinkEventSem = malloc(sizeof(tsem_t));
    tsem_init(appPriv->sinkEventSem, 0);
    appPriv->volumeEventSem = malloc(sizeof(tsem_t));
    tsem_init(appPriv->volumeEventSem, 0);
  }
  tsem_init(appPriv->filereaderEventSem, 0);
  tsem_init(appPriv->decoderEventSem, 0);
  tsem_init(appPriv->eofSem, 0);

  /** initialising openmax */
  err = OMX_Init();
  if (err != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "The OpenMAX core can not be initialized. Exiting...\n");
    exit(1);
  } 

  

  if(flagUsingFFMpeg) {
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Using File Reader\n");
    /** file reader component name -- gethandle*/
    err = OMX_GetHandle(&appPriv->filereaderhandle, FILE_READER, NULL , &filereadercallbacks);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR, "FileReader Component Not Found\n");
      exit(1);
    }  
    err = OMX_GetExtensionIndex(appPriv->filereaderhandle,"OMX.ST.index.param.inputfilename",&eIndexParamFilename);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR,"\n error in get extension index\n");
			exit(1);
    } 
  }

  /** getting the handle of audio decoder */
  err = OMX_GetHandle(&appPriv->audiodechandle, COMPONENT_NAME_BASE, NULL , &audiodeccallbacks);
  if(err != OMX_ErrorNone) {
    DEBUG(DEB_LEV_ERR, "Audio Decoder Component Not Found\n");
		exit(1);
  } 
  DEBUG(DEFAULT_MESSAGES, "Component %s opened\n", COMPONENT_NAME_BASE);

  if (flagPlaybackOn) {
    err = OMX_GetHandle(&appPriv->audiosinkhandle, SINK_NAME, NULL , &audiosinkcallbacks);
    if(err != OMX_ErrorNone){
      DEBUG(DEB_LEV_ERR, "No sink found. Exiting...\n");
      exit(1);
    }

    DEBUG(DEFAULT_MESSAGES, "Getting Handle for Component %s\n", AUDIO_EFFECT);
    err = OMX_GetHandle(&appPriv->volumehandle, AUDIO_EFFECT, NULL , &volumecallbacks);
    if(err != OMX_ErrorNone){
      DEBUG(DEB_LEV_ERR, "No sink found. Exiting...\n");
      exit(1);
    }

    if((gain >= 0) && (gain <100)) {
      err = OMX_GetConfig(appPriv->volumehandle, OMX_IndexConfigAudioVolume, &sVolume);
      if(err!=OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"Error %08x In OMX_GetConfig 0 \n",err);
      }
      sVolume.sVolume.nValue = gain;
      DEBUG(DEFAULT_MESSAGES, "Setting Gain %d \n", gain);
      err = OMX_SetConfig(appPriv->volumehandle, OMX_IndexConfigAudioVolume, &sVolume);
      if(err!=OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"Error %08x In OMX_SetConfig 0 \n",err);
      }
    }
  }

  if (flagSetupTunnel) {
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Setting up Tunnel\n");
    if(flagUsingFFMpeg) {
      err = OMX_SetupTunnel(appPriv->filereaderhandle, 0, appPriv->audiodechandle, 0);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR, "Set up Tunnel Failed\n");
        exit(1);
      }
    }
    err = OMX_SetupTunnel(appPriv->audiodechandle, 1, appPriv->volumehandle, 0);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR, "Set up Tunnel Failed\n");
      exit(1);
    }
    err = OMX_SetupTunnel(appPriv->volumehandle, 1, appPriv->audiosinkhandle, 0);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR, "Set up Tunnel Failed\n");
      exit(1);
    }
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Set up Tunnel Completed\n");
  }

  if(flagUsingFFMpeg) {
    /** now set the filereader component to idle and executing state */
    OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
  }

  /*Send State Change Idle command to Audio Decoder*/
  DEBUG(DEB_LEV_SIMPLE_SEQ, "Send Command Idle to Audio Dec\n");
  err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
  if (flagPlaybackOn) {
    DEBUG(DEB_LEV_SIMPLE_SEQ, "Send Command Idle to Audio Sink\n");
    err = OMX_SendCommand(appPriv->volumehandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
    err = OMX_SendCommand(appPriv->audiosinkhandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
  }

  if(flagUsingFFMpeg) {
      /*Wait for File reader state change to */
    tsem_down(appPriv->filereaderEventSem);
    DEBUG(DEFAULT_MESSAGES,"File reader idle state \n");
  }

  tsem_down(appPriv->decoderEventSem);
  if (flagPlaybackOn) {
    tsem_down(appPriv->volumeEventSem);
    DEBUG(DEFAULT_MESSAGES,"volume state idle\n");
    tsem_down(appPriv->sinkEventSem);
    DEBUG(DEFAULT_MESSAGES,"audio sink state idle\n");
  }

  if (flagPlaybackOn) {
    err = OMX_SendCommand(appPriv->volumehandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR,"volume state executing failed\n");
			exit(1);
    }
    DEBUG(DEB_LEV_SIMPLE_SEQ,"waiting for  volume state executing\n");
    tsem_down(appPriv->volumeEventSem);

    DEBUG(DEB_LEV_SIMPLE_SEQ,"sending audio sink state executing\n");
    err = OMX_SendCommand(appPriv->audiosinkhandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR,"audio sink state executing failed\n");
			exit(1);
    }
    DEBUG(DEB_LEV_SIMPLE_SEQ,"waiting for  audio sink state executing\n");
    tsem_down(appPriv->sinkEventSem);
    DEBUG(DEB_LEV_SIMPLE_SEQ, "audio sink state executing successful\n");
  } 
  
  setHeader(&sComponentRole, sizeof(OMX_PARAM_COMPONENTROLETYPE));
  strcpy((char*)&sComponentRole.cRole[0], MP3_ROLE);

  while((dp = readdir(dirp)) != NULL) {
    int len = strlen(dp->d_name);

		if(len >= 3){
      
      if(strncmp(dp->d_name+len-4, ".mp3", 4) == 0){
        
        if(input_file!=NULL) {
          free(input_file);
          input_file=NULL;
        }

        input_file = malloc(strlen(stream_dir) * sizeof(char) + sizeof(dp->d_name) +1);
        strcpy(input_file,stream_dir);
				strcat(input_file, dp->d_name);

        DEBUG(DEFAULT_MESSAGES, "Input Mp3 File Name=%s\n",input_file);

        flagUsingFFMpeg = 1;

        strcpy((char*)&sComponentRole.cRole[0], MP3_ROLE);

      } else if(strncmp(dp->d_name+len-4, ".ogg", 4) == 0){
        
        if(input_file!=NULL) {
          free(input_file);
          input_file=NULL;
        }

        input_file = malloc(strlen(stream_dir) * sizeof(char) + sizeof(dp->d_name) +1);
        strcpy(input_file,stream_dir);
				strcat(input_file, dp->d_name);

        DEBUG(DEFAULT_MESSAGES, "Input Vorbis File Name=%s\n",input_file);

        flagUsingFFMpeg = 1;

        strcpy((char*)&sComponentRole.cRole[0], VORBIS_ROLE);
                
      } else if(strncmp(dp->d_name+len-4, ".aac", 4) == 0){
        
        if(input_file!=NULL) {
          free(input_file);
          input_file=NULL;
        }

        input_file = malloc(strlen(stream_dir) * sizeof(char) + sizeof(dp->d_name) +1);
        strcpy(input_file,stream_dir);
				strcat(input_file, dp->d_name);

        DEBUG(DEFAULT_MESSAGES, "Input AAC File Name=%s\n",input_file);

        flagUsingFFMpeg = 1;

        strcpy((char*)&sComponentRole.cRole[0], AAC_ROLE);
                
      } else {
        continue;
      }
    } else {
      continue;
    }

    
    /*Reset Global Variables*/
    tsem_reset(appPriv->eofSem);
    bEOS=OMX_FALSE;

    if (flagUsingFFMpeg) {
      DEBUG(DEB_LEV_SIMPLE_SEQ,"Sending Port Disable Command State Idle\n");
      /*Port Disable for filereader is sent from Port Settings Changed event of FileReader*/
      err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandPortDisable, 0, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"file reader port disable failed\n");
			  exit(1);
      }
      err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandPortDisable, OMX_ALL, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"audio decoder port disable failed\n");
			  exit(1);
      }

      err = OMX_SendCommand(appPriv->volumehandle, OMX_CommandPortDisable, 0, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"audio sink port disable failed\n");
			  exit(1);
      }
      
      DEBUG(DEB_LEV_SIMPLE_SEQ,"Waiting File reader Port Disable event \n");
      /*Wait for File Reader Ports Disable Event*/
      tsem_down(appPriv->filereaderEventSem);
      DEBUG(DEB_LEV_SIMPLE_SEQ,"File reader Port Disable State Idle\n");
      /*Wait for Audio Decoder Ports Disable Event*/
      tsem_down(appPriv->decoderEventSem);
      tsem_down(appPriv->decoderEventSem);

      tsem_down(appPriv->volumeEventSem);

      err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
      tsem_down(appPriv->decoderEventSem);
    }


    DEBUG(DEB_LEV_SIMPLE_SEQ,"Setting Role\n");

    err = OMX_SetParameter(appPriv->audiodechandle,OMX_IndexParamStandardComponentRole,&sComponentRole);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR,"\n error in input audio format - exiting\n");
      exit(1);
    }

    if(flagUsingFFMpeg) {
      /** setting the input audio format in file reader */
      DEBUG(DEB_LEV_SIMPLE_SEQ,"FileName Param index : %x \n",eIndexParamFilename);
      err = OMX_SetParameter(appPriv->filereaderhandle,eIndexParamFilename,input_file);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"\n error in input audio format - exiting\n");
        exit(1);
      }
    }
    
    if (flagUsingFFMpeg) {
      DEBUG(DEB_LEV_SIMPLE_SEQ,"Sending Port Enable Command State Idle\n");

      err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
      tsem_down(appPriv->decoderEventSem);

      err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandPortEnable, 0, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"file reader port enable failed\n");
			  exit(1);
      }
      err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandPortEnable, OMX_ALL, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"audio decoder port enable failed\n");
			  exit(1);
      }

      err = OMX_SendCommand(appPriv->volumehandle, OMX_CommandPortEnable, 0, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"audio sink port enable failed\n");
			  exit(1);
      }
      
      DEBUG(DEB_LEV_SIMPLE_SEQ,"Waiting File reader Port Disable event \n");
      /*Wait for File Reader Ports Disable Event*/
      tsem_down(appPriv->filereaderEventSem);
      DEBUG(DEB_LEV_SIMPLE_SEQ,"File reader Port Disable State Idle\n");
      /*Wait for Audio Decoder Ports Disable Event*/
      tsem_down(appPriv->decoderEventSem);
      tsem_down(appPriv->decoderEventSem);
      
      tsem_down(appPriv->volumeEventSem);

      
    }

    if(flagUsingFFMpeg) {
      err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"file reader state executing failed\n");
			  exit(1);
      }
      /*Wait for File reader state change to executing*/
      tsem_down(appPriv->filereaderEventSem);
      DEBUG(DEFAULT_MESSAGES,"File reader executing state \n");
    }

    err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
    if(err != OMX_ErrorNone) {
      DEBUG(DEB_LEV_ERR,"audio decoder state executing failed\n");
      exit(1);
    }
    
    DEBUG(DEB_LEV_SIMPLE_SEQ,"Waiting for audio dec state exec\n");
    /*Wait for decoder state change to executing*/
    tsem_down(appPriv->decoderEventSem);

    DEBUG(DEB_LEV_SIMPLE_SEQ,"All Component state changed to Executing\n");
    
    DEBUG(DEFAULT_MESSAGES,"Waiting for  EOS = %d\n",appPriv->eofSem->semval);

    if (seek==1) {

      DEBUG(DEFAULT_MESSAGES,"Sleeping for 5 Secs \n");
      /* Play for 5 Secs */
      sleep(5);
      DEBUG(DEFAULT_MESSAGES,"Sleep for 5 Secs is over\n");

      /*Then Pause the filereader component*/
      err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StatePause, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"file reader state executing failed\n");
			  exit(1);
      }
      /*Wait for File reader state change to Pause*/
      tsem_down(appPriv->filereaderEventSem);

      setHeader(&sTimeStamp, sizeof(OMX_TIME_CONFIG_TIMESTAMPTYPE));
      sTimeStamp.nPortIndex=0;
      /*Seek to 30 secs and play for 10 secs*/
      sTimeStamp.nTimestamp = 2351*38*30; // 23.51ms*38fps*30secs
      //sTimeStamp.nTimestamp = 2351*38*60*3; // 23.51ms*38fps*60secs*4mins
      DEBUG(DEFAULT_MESSAGES, "nTimestamp %llx \n", sTimeStamp.nTimestamp);
      err = OMX_SetConfig(appPriv->filereaderhandle, OMX_IndexConfigTimePosition, &sTimeStamp);
      if(err!=OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"Error %08x In OMX_SetParameter 0 \n",err);
      }

      err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
      if(err != OMX_ErrorNone) {
        DEBUG(DEB_LEV_ERR,"file reader state executing failed\n");
			  exit(1);
      }
      /*Wait for File reader state change to Pause*/
      tsem_down(appPriv->filereaderEventSem);

      DEBUG(DEFAULT_MESSAGES,"Sleeping for 10 Secs \n");
      /*Play for 10 secs*/
      sleep(10);
      DEBUG(DEFAULT_MESSAGES,"Sleep for 10 Secs is over\n");

      if(!bEOS) {
        /*Then Pause the filereader component*/
        err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StatePause, NULL);
        if(err != OMX_ErrorNone) {
          DEBUG(DEB_LEV_ERR,"file reader state executing failed\n");
			    exit(1);
        }
        /*Wait for File reader state change to Pause*/
        tsem_down(appPriv->filereaderEventSem);

        /*Seek to 5 mins or EOF*/
        sTimeStamp.nTimestamp = 2351*38*60*5; // 23.51ms*38fps*30secs
        //sTimeStamp.nTimestamp = 2351*38*60*3; // 23.51ms*38fps*60secs*4mins
        DEBUG(DEFAULT_MESSAGES, "nTimestamp %llx \n", sTimeStamp.nTimestamp);
        err = OMX_SetConfig(appPriv->filereaderhandle, OMX_IndexConfigTimePosition, &sTimeStamp);
        if(err!=OMX_ErrorNone) {
          DEBUG(DEB_LEV_ERR,"Error %08x In OMX_SetParameter 0 \n",err);
        }

        err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StateExecuting, NULL);
        if(err != OMX_ErrorNone) {
          DEBUG(DEB_LEV_ERR,"file reader state executing failed\n");
			    exit(1);
        }
        /*Wait for File reader state change to Pause*/
        tsem_down(appPriv->filereaderEventSem);
      }
    }

    tsem_down(appPriv->eofSem);

    DEBUG(DEFAULT_MESSAGES,"Received EOS \n");
    /*Send Idle Command to all components*/
    DEBUG(DEFAULT_MESSAGES, "The execution of the decoding process is terminated\n");
    if(flagUsingFFMpeg) {
      err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
    }
    err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
    
    if(flagUsingFFMpeg) {
      tsem_down(appPriv->filereaderEventSem);
      DEBUG(DEFAULT_MESSAGES,"File reader idle state \n");
    }
    tsem_down(appPriv->decoderEventSem);
    
    DEBUG(DEFAULT_MESSAGES, "All component Transitioned to Idle\n");

  } /*Loop While Play List*/

  if (flagPlaybackOn) {
    err = OMX_SendCommand(appPriv->volumehandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
    err = OMX_SendCommand(appPriv->audiosinkhandle, OMX_CommandStateSet, OMX_StateIdle, NULL);
  }

  if (flagPlaybackOn) {
    tsem_down(appPriv->volumeEventSem);
    tsem_down(appPriv->sinkEventSem);
  }
  /*Send Loaded Command to all components*/
  if(flagUsingFFMpeg) {
    err = OMX_SendCommand(appPriv->filereaderhandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
  }
  err = OMX_SendCommand(appPriv->audiodechandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
  if (flagPlaybackOn) {
    err = OMX_SendCommand(appPriv->volumehandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
    err = OMX_SendCommand(appPriv->audiosinkhandle, OMX_CommandStateSet, OMX_StateLoaded, NULL);
  }

  DEBUG(DEFAULT_MESSAGES, "Audio dec to loaded\n");

  if(flagUsingFFMpeg) {
    tsem_down(appPriv->filereaderEventSem);
    DEBUG(DEFAULT_MESSAGES,"File reader loaded state \n");
  }
  tsem_down(appPriv->decoderEventSem);
  if (flagPlaybackOn) {
    tsem_down(appPriv->volumeEventSem);
    tsem_down(appPriv->sinkEventSem);
  }

  if(input_file!=NULL) {
    free(input_file);
    input_file=NULL;
  }

  closedir(dirp);

  DEBUG(DEFAULT_MESSAGES, "All components released\n");

  /** freeing all handles and deinit omx */
  OMX_FreeHandle(appPriv->audiodechandle);

  DEBUG(DEB_LEV_SIMPLE_SEQ, "audiodec dec freed\n");
  
  if(flagUsingFFMpeg) {
    OMX_FreeHandle(appPriv->filereaderhandle);
    DEBUG(DEB_LEV_SIMPLE_SEQ, "filereader freed\n");
  }

  if (flagPlaybackOn) {
    OMX_FreeHandle(appPriv->volumehandle);
    DEBUG(DEB_LEV_SIMPLE_SEQ, "volume component freed\n");
    OMX_FreeHandle(appPriv->audiosinkhandle);
    DEBUG(DEB_LEV_SIMPLE_SEQ, "audiosink freed\n");
  }

  OMX_Deinit();

  DEBUG(DEB_LEV_SIMPLE_SEQ, "All components freed. Closing...\n");

  free(appPriv->filereaderEventSem);
  appPriv->filereaderEventSem = NULL;

  free(appPriv->decoderEventSem);
  appPriv->decoderEventSem = NULL;
  if (flagPlaybackOn) {
    free(appPriv->volumeEventSem);
    appPriv->volumeEventSem = NULL;

    free(appPriv->sinkEventSem);
    appPriv->sinkEventSem = NULL;
  }

  free(appPriv->eofSem);
  appPriv->eofSem = NULL;
  free(appPriv);
  appPriv = NULL;

  if(input_file) {
    free(input_file);
  }

  return 0;
}	
예제 #15
0
static void process_options (int argc, char *argv[])
{
	int error = 0;
	int max_cpus = sysconf(_SC_NPROCESSORS_CONF);
	int thistracelimit = 0;

	for (;;) {
		int option_index = 0;
		/** Options for getopt */
		static struct option long_options[] = {
			{"affinity", optional_argument, NULL, 'a'},
			{"breaktrace", required_argument, NULL, 'b'},
			{"distance", required_argument, NULL, 'd'},
			{"fork", optional_argument, NULL, 'f'},
			{"interval", required_argument, NULL, 'i'},
			{"loops", required_argument, NULL, 'l'},
			{"priority", required_argument, NULL, 'p'},
			{"smp", no_argument, NULL, 'S'},
			{"threads", optional_argument, NULL, 't'},
			{"help", no_argument, NULL, '?'},
			{NULL, 0, NULL, 0}
		};
		int c = getopt_long (argc, argv, "a::b:d:f::i:l:p:St::",
			long_options, &option_index);
		if (c == -1)
			break;
		switch (c) {
		case 'a':
			if (smp) {
				warn("-a ignored due to --smp\n");
				break;
			}
			if (optarg != NULL) {
				affinity = atoi(optarg);
				setaffinity = AFFINITY_SPECIFIED;
			} else if (optind<argc && atoi(argv[optind])) {
				affinity = atoi(argv[optind]);
				setaffinity = AFFINITY_SPECIFIED;
			} else {
				setaffinity = AFFINITY_USEALL;
			}
			break;
		case 'b': thistracelimit = atoi(optarg); break;
		case 'd': distance = atoi(optarg); break;
		case 'f':
			if (optarg != NULL) {
				wasforked = 1;
				if (optarg[0] == 's')
					wasforked_sender = 1;
				else if (optarg[0] == 'r')
					wasforked_sender = 0;
				wasforked_threadno = atoi(optarg+1);
			} else
				mustfork = 1;
			break;
		case 'i': interval = atoi(optarg); break;
		case 'l': max_cycles = atoi(optarg); break;
		case 'p': priority = atoi(optarg); break;
		case 'S':
			smp = 1;
			num_threads = max_cpus;
			setaffinity = AFFINITY_USEALL;
			break;
		case 't':
			if (smp) {
				warn("-t ignored due to --smp\n");
				break;
			}
			if (optarg != NULL)
				num_threads = atoi(optarg);
			else if (optind<argc && atoi(argv[optind]))
				num_threads = atoi(argv[optind]);
			else
				num_threads = max_cpus;
			break;
		case '?': error = 1; break;
		}
	}

	if (!wasforked) {
		if (setaffinity == AFFINITY_SPECIFIED) {
			if (affinity < 0)
				error = 1;
			if (affinity >= max_cpus) {
				fprintf(stderr, "ERROR: CPU #%d not found, "
				    "only %d CPUs available\n",
				    affinity, max_cpus);
				error = 1;
			}
		}

		if (num_threads < 1 || num_threads > 255)
			error = 1;

		if (priority < 0 || priority > 99)
			error = 1;

		if (priority && smp)
			sameprio = 1;

		tracelimit = thistracelimit;
	}
	if (error)
		display_help ();
}
예제 #16
0
int main(int argc, char **argv)
{
    cardmanager_t* CTX;
    cardreader_t* READER;
    int opt;
    int opt_index = 0;
    int run_gui = 1;
    char* reader_name = NULL;
    char* exec_command = NULL;

#ifndef _WIN32
    SSL_load_error_strings();
#endif

    signal(SIGSEGV, save_what_can_be_saved);

    path_config_init();

    log_open_file();

    while ((opt = getopt_long(argc,argv,"r:e:vh",long_options,&opt_index))!=-1)
    {
        switch (opt)
        {
        case 'r':
            reader_name = g_strdup(optarg);
            break;
        case 'e':
            exec_command = optarg;
            break;
        case 'v':
            display_readers_and_version();
            run_gui = 0;
            break;
        default:
            display_help(argv[0]);
            run_gui = 0;
        }
    }

    if (run_gui)
    {
        /* if we want threads:
           gdk_threads_init();
           gdk_threads_enter();
         */

        gui_init(&argc,&argv);

        gui_create();

        log_printf(LOG_INFO,"Running %s",system_string_info());

        install_dot_file();

        luax_init();


        CTX = cardmanager_new();

        if (reader_name == NULL)
        {
            reader_name = gui_select_reader(cardmanager_count_readers(CTX),
                                            cardmanager_reader_name_list(CTX));
        }

        READER = cardreader_new(reader_name);

        cardmanager_free(CTX);

        if (READER)
        {
            luax_set_card_reader(READER);

            cardreader_set_callback(READER,gui_readerview_print,NULL);

            if (exec_command)
                g_idle_add(run_command_from_cli,exec_command);
            else
                update_cardpeek();
            /*else
              g_idle_add(run_update_checks,NULL);
             */
            gui_run();

            cardreader_free(READER);
        }
        else
        {
            fprintf(stderr,"Failed to open smart card reader '%s'.\n",reader_name);
            log_printf(LOG_ERROR,"Failed to open smart card reader '%s'.", reader_name);
        }

        luax_config_table_save();

        luax_release();

        /* if we want threads:
           gdk_threads_leave();
         */
    }

    if (reader_name) g_free(reader_name);

    log_close_file();

    path_config_release();

    ERR_free_strings();

    return 0;
}
예제 #17
0
void process_options (int argc, char *argv[])
{
	int error = 0;

	for (;;) {
		int option_index = 0;
		static const char *short_options = "blce:rd:o:v";
		static const struct option long_options[] = {
			{"help", no_argument, 0, 0},
			{"version", no_argument, 0, 0},
			{"bigendian", no_argument, 0, 'b'},
			{"littleendian", no_argument, 0, 'l'},
			{"content", no_argument, 0, 'c'},
			{"endianconvert", required_argument, 0, 'e'},
			{"datsize", required_argument, 0, 'd'},
			{"oobsize", required_argument, 0, 'o'},
			{"recalccrc", required_argument, 0, 'r'},
			{"verbose", no_argument, 0, 'v'},
			{0, 0, 0, 0},
		};

		int c = getopt_long(argc, argv, short_options,
				long_options, &option_index);
		if (c == EOF) {
			break;
		}

		switch (c) {
			case 0:
				switch (option_index) {
					case 0:
						display_help();
						break;
					case 1:
						display_version();
						break;
				}
				break;
			case 'v':
				verbose = 1;
				break;
			case 'b':
				target_endian = __BIG_ENDIAN;
				break;
			case 'l':
				target_endian = __LITTLE_ENDIAN;
				break;
			case 'c':
				dumpcontent = 1;
				break;
			case 'd':
				datsize = atoi(optarg);
				break;
			case 'o':
				oobsize = atoi(optarg);
				break;
			case 'e':
				convertendian = 1;
				strcpy (cnvfile, optarg);
				break;
			case 'r':
				recalccrc = 1;
				break;
			case '?':
				error = 1;
				break;
		}
	}

	if ((argc - optind) != 1 || error)
		display_help ();

	img = argv[optind];
}
예제 #18
0
int main(int argc, char *argv[]) {
   FILE  *fp;
   int c, i, interactive = 0, view_only=1,delete_tag=0,file_open,retcode=0;
   int want_id3=1,scantype=SCAN_NONE,fullscan_vbr=0;
   int show_techinfo=0,force_mode=0,quickscan=1;
   int new_track=0,new_genre=0,firstfilearg;
   id3tag new_tag;
   char *print_format=NULL;
   char error_msg[256];
   unsigned int g,n;
   int vbr_report=VBR_VARIABLE;
   mp3info mp3;


   new_tag.title[0]=new_tag.artist[0]=new_tag.album[0]=new_tag.year[0]=
   new_tag.comment[0]=new_tag.track[0]=new_tag.genre[0]=1;
   /* use something REALLY unlikely... -- so we could clear the tag... */

   if (argc < 2 ) /* Only command is given. Short help */ {
	   printf("%s %s\n"\
		  "\n  MP3Info comes with ABSOLUTELY NO WARRANTY.  This is free software, and\n"\
		  "  you are welcome to redistribute it under certain conditions.\n"\
		  "  See the file 'LICENSE' for more information.\n"\
		  "\nUse 'mp3info -h' for a usage summary or see the mp3info man page for a\n"\
		  "complete description.\n",VERSION,COPYRIGHT);
	   return 0;
   }



   while ((c=getopt(argc,argv,"vhGidfxFt:a:l:y:c:n:g:p:r:"))!=-1) {

	switch(c) {
		case 'v': /* View mode is now automatic when no changes are
			     made to the ID3 tag. This switch is accepted 
			     only for backward compatibility */
			break;
		case 'h':
			display_help(); return 0;
			break;
		case 'G':
			display_genres(alphagenreindex,typegenre); return 0;
			break;
		case 'i':
			view_only=0;
			interactive = 1;
			break;
		case 'd':
			view_only=0;
			delete_tag=1;
			break;
		case 'p':
			print_format=optarg;
			translate_escapes(print_format);
			want_id3=0;
			break;
	        case 'f':
			force_mode=1;
			break;
		case 'x':
			show_techinfo=1;
			break;
		case 't':
			strncpy(new_tag.title,optarg,TEXT_FIELD_LEN);
			view_only=0;
			break;
		case 'a':
			strncpy(new_tag.artist,optarg,TEXT_FIELD_LEN);
			view_only=0;
			break;
		case 'l':
			strncpy(new_tag.album,optarg,TEXT_FIELD_LEN);
			view_only=0;
			break;
		case 'y':
			strncpy(new_tag.year,optarg,INT_FIELD_LEN);
			view_only=0;
			break;
		case 'c':
			strncpy(new_tag.comment,optarg,TEXT_FIELD_LEN);
			view_only=0;
			break;
		case 'n':
			n=atoi(optarg);
			if(n <= 255) {
				new_tag.track[0] = (unsigned char) n;
				new_track=1;
				view_only=0;
			} else {
				fprintf(stderr,"Error: '%s' is not a valid track number.\n",optarg);
				fprintf(stderr,"Valid track numbers are integers from 0 to 255.\n");
				fprintf(stderr,"Use a value of '0' to remove the track number field\n");
				retcode |= 6;
				return retcode;
			}
			break;
		case 'g':
			g=get_genre(optarg);
			if(g <= 255) {
				new_tag.genre[0] = (unsigned char) g;
				new_genre=1;
				view_only=0;
			} else {
				fprintf(stderr,"Error: '%s' is not a recognized genre name or number.\n",optarg);
				fprintf(stderr,"Use the '-G' option to see a list of valid genre names and numbers\n");
				retcode |= 6;
				return retcode;
			}
			sscanf(optarg,"%u",&g);
			break;
		case 'r':
			switch(optarg[0]) {
				case 'a': vbr_report=VBR_AVERAGE; break;
				case 'm': vbr_report=VBR_MEDIAN; break;
				case 'v': vbr_report=VBR_VARIABLE; break;
				default:
					fprintf(stderr,"Error: %s is not a valid option to the VBR reporting switch (-r)\n",optarg);
					fprintf(stderr,"Valid options are 'a', 'm' and 'v'.  Run '%s -h' for more info.\n",argv[0]);
					retcode |= 6;
					return retcode;
			}
			break;
		case 'F': quickscan=0; break;
	}
   }

   if(!view_only)
	scantype=SCAN_QUICK;

   if(print_format) {
   	determine_tasks(print_format,&want_id3,&scantype,&fullscan_vbr,vbr_report);
   } else if(view_only) {
   	determine_tasks(ID3_FORMAT_STRING,&want_id3,&scantype,&fullscan_vbr,vbr_report);
	if(show_techinfo)
		determine_tasks(TECH_FORMAT_STRING,&want_id3,&scantype,&fullscan_vbr,vbr_report);
   }

   
   if(!quickscan && (scantype == SCAN_QUICK))
   	scantype=SCAN_FULL;

   firstfilearg=optind;

   for(i=optind;i < argc; i++) { /* Iterate over all filenames */
      file_open=0;
      if (view_only == 1) { 
        if ( !( fp=fopen(argv[i],"rb") ) ) {
  	        sprintf(error_msg,"Error opening MP3: %s",argv[i]);
                perror(error_msg);
		retcode |= 1;
        } else {
		file_open=1;
	}
      } else {
        if ( !( fp=fopen(argv[i],"rb+") ) ) {
  	        sprintf(error_msg,"Error opening MP3: %s",argv[i]);
                perror(error_msg);
	        retcode |= 1;
        } else {
		file_open=1;
	}
      }

      if(file_open == 1) {
	memset(&mp3,0,sizeof(mp3info));
	mp3.filename=argv[i];
	mp3.file=fp;
	get_mp3_info(&mp3,scantype,fullscan_vbr);
	
	if((scantype != SCAN_NONE) && !mp3.header_isvalid && !force_mode) {
		fprintf(stderr,"%s is corrupt or is not a standard MP3 file.\n",mp3.filename);
		retcode |= 2;
	}

	if(view_only) {
	   if(want_id3 && !mp3.id3_isvalid)
		fprintf(stderr,"%s does not have an ID3 1.x tag.\n",mp3.filename);

	    if(print_format) {
		format_output(print_format,&mp3,vbr_report);
            } else {

		if(mp3.id3_isvalid || (show_techinfo && mp3.header_isvalid))
  	          	format_output(FILENAME_FORMAT_STRING,&mp3,vbr_report);
            	
       		if(mp3.id3_isvalid)
			format_output(ID3_FORMAT_STRING,&mp3,vbr_report);

            	if(show_techinfo && mp3.header_isvalid)
			format_output(TECH_FORMAT_STRING,&mp3,vbr_report);

       	    	printf("\n");

	    }
   
	} else if(mp3.header_isvalid || force_mode) {

	     if(new_tag.title[0]!=1) {
		  strncpy(mp3.id3.title,new_tag.title,TEXT_FIELD_LEN);
	     }

	     if(new_tag.artist[0]!=1) {
		  strncpy(mp3.id3.artist,new_tag.artist,TEXT_FIELD_LEN);
	     }

	     if(new_tag.album[0]!=1) {
		  strncpy(mp3.id3.album,new_tag.album,TEXT_FIELD_LEN);
	     }

	     if(new_tag.comment[0]!=1) {
			strncpy(mp3.id3.comment,new_tag.comment,TEXT_FIELD_LEN);
	     }

	     if(new_track) {
		  mp3.id3.track[0]=new_tag.track[0];
		  if(new_tag.track[0] == '\0') {
		     pad(mp3.id3.comment,TEXT_FIELD_LEN);
		  }
	     }

	     if(new_tag.year[0]!=1) {
		  strncpy(mp3.id3.year,new_tag.year,INT_FIELD_LEN);
	     }

	     if(new_genre) {
		  mp3.id3.genre[0]=new_tag.genre[0];
	     }
  		  
	     if( interactive ) {
	 	  tagedit_curs(mp3.filename,i-firstfilearg+1,argc-firstfilearg,&(mp3.id3));
	     }
                  

               
             /* Finally! Get it done! */
             if(!delete_tag) {
	          write_tag(&mp3);
             }

	 } else {
		fprintf(stderr,"Use the -f switch to add ID3 info to this file anyway.\n");
	 }

         fclose(mp3.file);

         if(delete_tag && mp3.id3_isvalid) {
		truncate(mp3.filename,mp3.datasize);
	 }


      }

   }

   if(optind == argc) {
	fprintf(stderr,"No MP3 files specified!\n");
	retcode |= 8;
   }


   return retcode;

}