Ejemplo n.º 1
0
//eka, to dump temperature in transistor layer and map it
//back to structures in power model
void ThermTrace::BlockT2StrcTMap()
{
  
   //strTemp->resize(energyCntrNames_->size());
  // eka,Find mappings between variables and flp and 
  // copy temperature to each match (power model structure)
  //FIXME: Move the mapping to config, avoid doing it in runtime
  for(size_t id=0;id<flp.size();id++) { 
    for(size_t i=0; i<flp[id]->match.size(); i++) {
      for(size_t j=0; j<mapping.size(); j++) {
        if (grep(mapping[j].name, flp[id]->match[i])) {

          //LOG("mapping[%d].map[%d]=%d (%s -> %s)", 
          //    (int) j, (int) mapping[j].map.size(), (int) id, 
          //    flp[id]->match[i], mapping[j].name);
          //find index of match in energyCntrNames
          int index=-1;
          for (int ii=0; ii < (int) energyBundle->cntrs.size(); ii++){
						string name = energyBundle->cntrs[ii].getName();
            if (name.compare(flp[id]->match[i]) == 0){
              index = ii;
              break;
            }
          }
          if (index == -1){
            LOG("Could not find the map for <%s> in Power Counters.",flp[id]->match[i] );            
          }else{
            flp[id]->blk2strMap.push_back(index);
          }
        }
      }
    }
  }
}
Ejemplo n.º 2
0
TEST(TestMultiGrep, TestGrep6)
{
  std::string line;
  MultiGrep grep(2);
  grep.process("hi1\n", true); // x - M
  ASSERT_TRUE(grep.hasNext());
  grep.getNext(line);
  ASSERT_EQ("hi1\n", line);
  grep.process("hi2\n", false); // x
  ASSERT_TRUE(grep.hasNext());
  grep.getNext(line);
  ASSERT_EQ("hi2\n", line);
  grep.process("hi3\n", false); // x
  ASSERT_TRUE(grep.hasNext());
  grep.getNext(line);
  ASSERT_EQ("hi3\n", line);
  grep.process("hi4\n", false);
  ASSERT_FALSE(grep.hasNext());
  grep.process("hi5\n", false); // x
  ASSERT_FALSE(grep.hasNext());
  grep.process("hi6\n", false); // x
  ASSERT_FALSE(grep.hasNext());
  grep.process("hi7\n", true); // x - M
  ASSERT_TRUE(grep.hasNext());
  grep.getNext(line);
  ASSERT_EQ("hi5\n", line);
  ASSERT_TRUE(grep.hasNext());
  grep.getNext(line);
  ASSERT_EQ("hi6\n", line);
  ASSERT_TRUE(grep.hasNext());
  grep.getNext(line);
  ASSERT_EQ("hi7\n", line);
  ASSERT_FALSE(grep.hasNext());
}
Ejemplo n.º 3
0
/**
 * 5.10 grep
 * main 関数の引数
 */
int main(int argc, char *argv[])
{
	int	c, except = 0, number = 0;
	
	while( --argc > 0 && (*++argv)[0] == '-'){
		while(c = *++argv[0]){
			switch(c){
				case 'x':
					except = 1;
					break;
				case 'n':
					number = 1;
					break;
				default:
					printf("find: illegal option %c\n", c);
					argc = 0;
					break;
			}
		}
	}
	
	if(argc != 1){
		printf("Usage: find -x -n pattern\n");
		return -1;
	}else{
		return grep( *argv, number, except);
	}
}
Ejemplo n.º 4
0
int main(int argc, char *argv[])
{
    char* line;
    g_progname = argv[0];

    switch (argc) {
    case 2:
        break;
    case 1:
        die("too few arguments (need regexp pattern)");
    default:
        die("too many arguments (only one pattern accepted)");
    }

    while ((line = readln()) != NULL) grep(line, argv[1]);

    switch (errno) { /* find out why readln() couldn't get another line */
    case 0:
        break;
    case EIO:
        die("couldn't read from standard input");
    case ENOMEM:
        die("out of memory (can't store input)");
    }

    freeln(line);
    /* "TODO": More code here, that justifies bothering to call freeln()  *
     *         before program termination (which frees all heap memory).  */
    return EXIT_SUCCESS;
}
Ejemplo n.º 5
0
int main(int argc, char** argv)
{
    // grep файл подстрока
    // grep -l директория подстрока

    // Проверка на корректность числа аргументов
    if( (argc != 3) && (argc != 4) )
    {
        perror("Uncorrect arguments number");
        _exit(1);
    }

    char* file_name;
    char* str;

    // Выполнение функции grep
    if(strcmp(argv[1], "-l"))
    {
        file_name = argv[1];
        str = argv[2];

        grep(file_name, str);
    }
    // Выполнение функции grep -l
    else
    {
        file_name = argv[2];
        str = argv[3];

        grep_l(file_name, str);
    }

    return 0;
}
Ejemplo n.º 6
0
void ThermTrace::loadLkgCoefs(){
  // eka,Find mappings between variables and flp and 
  // to find the device type for each flp block
  for(size_t id=0;id<flp.size();id++) { 
    for(size_t i=0; i<flp[id]->match.size(); i++) {
      for(size_t j=0; j<mapping.size(); j++) {
        if (grep(mapping[j].name, flp[id]->match[i])) {
          //set the device type
          switch(energyBundle->cntrs[j].getDevType()){
            case 0:
              flp[id]->devType.set(hpThLeakageCoefs);
              break;
            case 1:
             flp[id]->devType.set(lstpThLeakageCoefs);
              break;
            case 2:
              flp[id]->devType.set(lpThLeakageCoefs);
              break; 
            default:break;

          }
        }
      }
    }
  }
}
Ejemplo n.º 7
0
/* "match" tests whether the source matches the pattern exactly */
boolean match(Char *source_, Char *pattern_)
{
  Char source[256], pattern[256];
  static Char target[256] = "";

  strcpy(source, source_);
  strcpy(pattern, pattern_);
  grep(source, pattern, target);
  return (*source == '\0' && *pattern == '\0');
}
Ejemplo n.º 8
0
/* read a line, trying to find 'variable = value' 
   Currently groks two constructs:
   VAR=value
   : {VAR=value}
   using regex to analyze them.
   The variable is added to the symbol table. In the first case, it
   overrides an old value, not in the second case.
 */
boolean parse_variable(string line)
{
  char **vars;

  static char *r1 = "^[[:space:]]*([[:alnum:]_]+)=[[:space:]]*([^[:space:]]*)[[:space:]]*.*$";
  static char *r2 = "^:[[:space:]]+\\$\\{([[:alnum:]_]+)=([^\\}]*)\\}[[:space:]]*.*$";

  if ((vars = grep(r1, line, 2))) {
    setval(vars[1], vars[2]);
    return true;
  }
  else if ((vars = grep(r2, line, 2))) {
    setval_default(vars[1], vars[2]);
    return true;
  }
  else
    WARNING1("The following line has not been parsed:\n%s\n", line);
  return false;
}
Ejemplo n.º 9
0
/* "translate" replaces the pattern by the target in the source. */
Char *translate(Char *Result, Char *source_, Char *pattern_, Char *target_)
{
  Char source[256], pattern[256], target[256];

  strcpy(source, source_);
  strcpy(pattern, pattern_);
  strcpy(target, target_);
  grep(source, pattern, target);
  return strcpy(Result, target);
}
Ejemplo n.º 10
0
/* find:  print lines that match pattern from 1st arg */
int main(int argc, char *argv[])
{
    char *line;
    long lineno = 0;
    int c, number = 0, found = 0;

    while (--argc > 0 && (*++argv)[0] == '-')
        while ((c = *++argv[0]))
            switch (c) {
            case 'x':
                except = 1;
                break;
            case 'n':
                number = 1;
                break;
            default:
                printf("find: illegal option %c\n", c);
                argc = 0;
                found = -1;
                break;
            }
    if (argc < 1) {
        fprintf(stderr, "Usage: find -x -n pattern\n");
        exit(1);
    } else {
        char *pattern = *argv++; argc--;
        if (argc > 0)
            while (argc-- > 0) {
                FILE *f = fopen(*argv, "r");
                if (f == NULL) {
                    fprintf(stderr, "Unable to read file %s\n", *argv);
                } else {
                    found += grep(pattern, f);
                }
                fclose(f);
                argv++;
            }
        else
            found += grep(pattern, stdin);
    }
    return found;
}
int main(int argc, char *argv[])
{

    int n_tasks, rank, rc, tag=1;
    unsigned int i = 0;
    unsigned int n_linhas, size_job;
    unsigned int job[2];

    MPI_Status Stat;
    MPI_Init(&argc,&argv);
    MPI_Comm_size(MPI_COMM_WORLD, &n_tasks);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);


    if(rank == 0)
    {
        n_linhas = numero_de_linhas();

        size_job = n_linhas/(n_tasks-1);
        if((n_linhas % (n_tasks-1)) != 0)
            size_job++;

        //printf("size_job: %d\n\n",size_job);


        for(i=1;i<n_tasks;i++)
        {
            job[0] = (i-1)*size_job + 1;
            job[1] = i*size_job;

            if(job[0] > n_linhas)
                job[0] = n_linhas;
            if(job[1] > n_linhas)
                job[1] = n_linhas;

            rc = MPI_Send(&job, 2, MPI_INT, i, tag, MPI_COMM_WORLD);

        }
    }

    else
    {
        rc = MPI_Recv(&job, 2, MPI_INT, 0, tag, MPI_COMM_WORLD, &Stat);
        //printf("rank%d: %d a %d\n",rank,job[0],job[1]);

        grep(rank,job[0],job[1]);
    }


    MPI_Finalize();

    return 0;
}
Ejemplo n.º 12
0
Archivo: grep.c Proyecto: darius/ung
void real_main (int argc, char *const argv[]) {
  int found = 0;
  int i = 1;
  panic_code = 2;
  for (; i < argc && argv[i][0] == '-'; ++i)
    parse_options (argv[i] + 1);
  if (i == argc)
    usage ();
  else if (i + 1 == argc)
    found = grep (argv[i], stdin, NULL);
  else {
    const char *regexp = argv[i++];
    showing_filenames = (1 < argc - i);
    for (; i < argc; ++i) {
      FILE *in = must_fopen (argv[i], "r");
      found |= grep (regexp, in, argv[i]);
      must_fclose (in, argv[i]);
    }
  }
  exit (!found);
}
Ejemplo n.º 13
0
int main( int argc, char *argv[] ){
  char *pattern;
  int found = 0;
  FILE *fp;

  while( --argc > 0 && (*++argv)[0] == '-' )
     while( *++argv[ 0 ] )
      switch( **argv ){
      case 'x': except = 1; break;
      case 'n': number = 1; break;
      case 'w': name   = 1; break;
      default:
        fprintf( stderr, "grep: illegal option %c\n", **argv );
        return 0;
      }

  if( argc == 0 ){
    fprintf( stderr, "Usage: grep -x -n -w  pattern files\n" );
    return 0;
  }

  pattern = *argv++;

  if( !*argv ) found = grep( pattern, stdin, "stdin" );
  else
    while( *argv ){
      if( (fp = fopen( *argv, "r" )) == NULL ){
        fprintf( stderr, "grep: %s: error opening file\n", *argv );
        return 0;
      } else {
        found += grep( pattern, fp, *argv );
        fclose( fp );
      }

      argv++;
    }

  return found;
}
Ejemplo n.º 14
0
BoincError TestBoincHttpPostForm(void * data) 
{
  post_index = 0;
  char* form  = "go=1&search=boinc";

  BoincError res = boincHttpPost("http://fr.wikipedia.org/wiki/Sp%C3%A9cial:Recherche", TMPFILE, strlen(form), TestBoincHttpPostCallback, form);
  if (!res) {
    if (grep(TMPFILE, "BOINC"))
      if (zgrep(TMPFILE, "BOINC"))
        res = boincErrorCreate(kBoincError, 999, "String 'BOINC' not found in result file");
  }
  remove(TMPFILE);
  return res;
}
Ejemplo n.º 15
0
int main (void) {

  int  sdb1,
       mnt,
       proc;

  while (1) {
    sdb1 = grep ("sdb1", "/proc/diskstats");
    mnt  = grep ("sdb1", "/proc/mounts");

    if (sdb1 && !mnt) {
      if ((proc = pgrep (VICTIM)) != 0)
        kill (proc, SIGTERM);   
      mount (SOURCE, TARGET, "vfat", MS_RDONLY, NULL);
    }
    if (!sdb1 && mnt) {
      if ((proc = pgrep (VICTIM)) != 0)
        kill (proc, SIGTERM);   
      umount (TARGET);
    }
    sleep (DELAY);
  }
}
Ejemplo n.º 16
0
int main (int argc, char * * argv) {
    cppshell::Command ls("ls");
    cppshell::Command grep("grep");
    cppshell::Command sort("sort");

    // auto s = (ls % "-lh" % "/tmp")();
    // auto s = (ls[{"-lh", "/tmp"}] | grep[{"a"}] | sort) ();
    auto s = (ls[{"-lh", "/tmp"}] | grep[{"a"}]) ();
    // auto s = (ls[{"-lh", "/tmp"}]) ();
    // ls[{"-lh", "/tmp", "/"}];

    std::cout << "stdout :" << std::endl;
    std::cout << s << std::endl;

    return 0;
}
Ejemplo n.º 17
0
TEST(TestMultiGrep, TestGrep7)
{
  std::string line;
  MultiGrep grep(0); // no multiple lines, no buffering
  grep.process("hi1\n", true); // x - M
  ASSERT_TRUE(grep.hasNext());
  grep.getNext(line);
  ASSERT_EQ("hi1\n", line);
  grep.process("hi2\n", false);
  ASSERT_FALSE(grep.hasNext());
  grep.process("hi3\n", true); // x - M
  ASSERT_TRUE(grep.hasNext());
  grep.getNext(line);
  ASSERT_EQ("hi3\n", line);
  ASSERT_FALSE(grep.hasNext());
}
Ejemplo n.º 18
0
int
cycle (mpf_t x) {

   char s[10000];
   char srch[SSIZE+1];
   int i;
   mp_exp_t e;
   mpf_get_str (s, &e, 10, 10000, x);
   
   // copy a search string
   for (i=0; i<SSIZE; i++)
     srch[i] = s[i+SSIZE]; 
   srch[i]='\0';

  return grep(srch, s+SSIZE+1);
}
Ejemplo n.º 19
0
void Index::scan(QString path, QString match)
{
    QString spec;
    QString name;
    if(path.isEmpty())
        spec = QDir::currentPath();
    else
        spec = QDir::currentPath() + QDir::separator() + path;

    QDir dir(spec);
    if(!dir.exists())
        return;

    QDir::Filters filter = QDir::Files | QDir::NoDot;
    QDir::SortFlags sorting = QDir::SortFlags(QDir::Name);

    if(!Main::casefilter)
        sorting |= QDir::IgnoreCase;

    QStringList dirs = dir.entryList(QDir::AllDirs, sorting);
    dir.setNameFilters(filters);
    QStringList list = dir.entryList(filter, sorting);

    for(unsigned pos = 0; pos < (unsigned)dirs.size(); ++pos) {
        if(dirs[pos][0] == '.')
            continue;
        if(path.isEmpty())
            scan(dirs[pos], match);
        else
            scan(path + QDir::separator() + dirs[pos], match);
    }

    for(unsigned pos = 0; pos < (unsigned)list.size(); ++pos) {
        if(list[pos][0] == '.')
            continue;
        if(path.isEmpty())
            name = list[pos];
        else
            name = path + QDir::separator() + list[pos];

        if(!match.isEmpty() && !grep(name, match))
            continue;

        names << name;
        ++rows;
    }
}
Ejemplo n.º 20
0
int 
main()
{
	int c;
	char ch;
	int j;
	char str[10];
	int ret = 0;

	while (gi < MAX) {
			
		printf ("enter your choice\n\n");
		printf ("D or dfor display\n\n");
		printf ("I or ifor insert a line\n");
		printf ("s or S for search\n\n");
		scanf ("%c", &ch);

		switch(ch) {

		case 'd': case 'D':
			for (j = 0; j < gi; j++)
				printf ("%s\n", array[j]);
			break;

		case 'i': case 'I':
			getline1(&array[gi++]);
			break;

		case 's': case 'S':
			printf ("enter the string");
			scanf ("%s", str);
			ret = grep(array, str);
			if(ret)
				printf("string found at line no %d \n", ret);
			else
				printf ("string not found\n");
			break;

		default:
			continue;
		}
	}
					
}
Ejemplo n.º 21
0
void putlog (char *name, char *befbuf)
//*************************************************************************
//
//*************************************************************************
{
#ifdef __FLAT__
  html_putf("<b>%s:</b> <a href=cmd?cmd=slog>Syslog</a> | ", ms(m_otherlogs));
  html_putf("<a href=cmd?cmd=erlog>Erase</a> | ");
  html_putf("<a href=cmd?cmd=swaplog>Swap</a> | ");
  html_putf("<a href=cmd?cmd=pwlog>PW</a> | ");
  html_putf("<a href=cmd?cmd=unknown>Unknown</a> | ");
  html_putf("<a href=cmd?cmd=rlog>Reject</a> | ");
  html_putf("<a href=cmd?cmd=sfhold>S&F-Hold</a>");
  if ((m.tcpiptrace == 1) || (m.tcpiptrace == 8))
    html_putf(" | <a href=cmd?cmd=httplog>HTTP</a>");
  if ((m.tcpiptrace == 2) || (m.tcpiptrace == 8))
    html_putf(" | <a href=cmd?cmd=nntplog>NNTP</a>");
  if ((m.tcpiptrace == 3) || (m.tcpiptrace == 8))
    html_putf(" | <a href=cmd?cmd=pop3log>POP3</a>");
  if ((m.tcpiptrace == 4) || (m.tcpiptrace == 8))
    html_putf(" | <a href=cmd?cmd=smtplog>SMTP</a>");
  if ((m.tcpiptrace == 5) || (m.tcpiptrace == 8))
    html_putf(" | <a href=cmd?cmd=ftplog>FTP</a>");
//  html_putf("<form method=get action=\"/cmd\" target=\"txt\">\n");
//  html_putf("Search: <input name=\"search\" value=\"\" size=40>");
//  html_putf("<input type=\"submit\" value=\"Execute\">");
  html_putf("<br><hr>");
#endif
  if (*befbuf)
  { // Optionen durchreichen
    if (b->optminus & o_i) b->optplus |= o_i;
    // wenn nicht explizit "-i-", ist "-i" default
    befbuf += blkill(befbuf);
    grep(name, befbuf, b->optplus);
  }
  else
  {
    fileio_text fio;
    fio.usefile(name);
    fio.settail(-2500);
    fio.tx();
  }
}
Ejemplo n.º 22
0
int main(int argc,char * argv[])
{
    int fd,offset=0,bytesread,readchar;
    char buff[1024];
    char line[1024];
    if(argc < 3)
    {
        fd = 0;
    }
    else
    {
        fd = open(argv[2],READ);
    }

    //get lines from file, print them if they match pattern
    //no regex support required(thank god)
    
    bytesread = read(fd,buff,1024);
    //printf("fd = %d,buff = %s,bytes read = %d\r\n",fd,buff,bytesread);

    do 
    {
        //printf("\r\nBefore: buff: %s\r\n line: %s\r\n offset: %d\r\n",buff,line,offset);
        readchar = readUntilChar(buff,line,'\n',&offset);
        //printf("Chars read %d",readchar);
        if (offset == 1024)
        {
            //we have a split line to handle
            offset = 0;
            bytesread = read(fd,buff,1024);
            if (bytesread < 1024)
            {
                buff[bytesread] = '\0';
            }
            readchar = readUntilChar(buff,line+readchar,'\n',&offset);
        }
        if (grep(argv[1],line)==1)
        {
            printf("%s\r\n",line);
        }
    }while(readchar != -1 );
}
Ejemplo n.º 23
0
Archivo: grep.c Proyecto: lufb/code
int
main(int argc, char *argv[])
{
    int                 c;
    char                *pfind = NULL;
    int                 err;

    static struct option const long_options[] =
    {
        {"help", 0, NULL, 'h'},
        {NULL, 0, NULL, 0}
    };
    exit_status = EXIT_SUCESS;
    program_name = argv[0];
    while((c = getopt_long(argc, argv,
                           "h", long_options, NULL)) != -1)
    {
        switch(c)
        {
            case 'h':
            case 'H':
                grep_usage_exit(EXIT_SUCESS);
                break;
            default:
                grep_usage_exit(EXIT_FAILURE);
                break;
        }
    }

    if(argc - optind < 2)
        grep_usage_exit(EXIT_FAILURE);

    pfind = argv[optind++];
    while(optind < argc)
    {
        if((err = grep(pfind, argv[optind++])) != 0)
            exit_status = EXIT_FAILURE;
    }

    exit(exit_status);
}
Ejemplo n.º 24
0
bool CmdDoc::exec(CmdHelper* ch)
{
  if(!init(ch)) return false;

  mCmd->regStdOpts("grep");

  if(mCmd->wantHelp())
  {
    mCmd->inOptBrief("grep", tr("Search in documentation"));
  }

  if(mCmd->isMissingParms())
  {
    if(mCmd->printThisWay("[<FileNumber>|<Pattern>]")) return !hasError();

    mCmd->printComment(tr(
      "Without any parameter will a table of all available documentation shown "
      "and you prompt to enter a file number to display the document. After quit "
      "reading the doc you will ask again to enter a file number. Hit RETURN "
      "to leave the loop."));
    mCmd->printComment(tr(
      "When you give the <FileNumber> as parameter will the document shown immediately "
      "and you will not ask again for a new file number. You can limit the table "
      "by give a <Pattern> matching the document name. If the result is only one "
      "file will it shown immediately."));
    mCmd->printNote(tr(
      "Text files are shown by UNIX 'less' command whereas other files will called "
      "with 'xdg-open' to use your preferred application."));

    mCmd->aided();
    return !hasError();
  }

  if(mCmd->has("grep"))     grep();
  else                      list();

  return !hasError();
}
int bulBeni(char *arguman, char *sstring, int lineNum)
{
    struct stat stDirInfo;
    struct dirent * stFiles;
    DIR * stDirIn;
    pid_t  pid;
    char szFullName[MAXPATHLEN]; /* dosya isimleri icin */
    char szDirectory[MAXPATHLEN];
    struct stat stFileInfo;
	int fd[2]; /* For pipe */
	char bufin[BUFSIZE];
    int countLess=0; /* for  Less count */
    char chr; /* for getchar() */

    strncpy( szDirectory, arguman, MAXPATHLEN - 1 );

    /* Error check */
    if (lstat( szDirectory, &stDirInfo) < 0)
    {
        perror (szDirectory);
        return;
    }

    if (!S_ISDIR(stDirInfo.st_mode))
        return;
    if ((stDirIn = opendir( szDirectory)) == NULL) /* klasor acilir */
    {
        perror( szDirectory );
        return;
    }

    /* klasorun icerigi okunur */
    while (( stFiles = readdir(stDirIn)) != NULL)
    {
        sprintf(szFullName, "%s/%s", szDirectory, stFiles -> d_name );

        if (lstat(szFullName, &stFileInfo) < 0)
           perror ( szFullName );

        /* klasor mu diye bakilir, kalsor ise onunda icine girilir. */
        if (S_ISDIR(stFileInfo.st_mode))
        {
            if ((strcmp(stFiles->d_name , "..")) && (strcmp(stFiles->d_name , ".")))
            {
                /* recursive olarak ic icedosyalara girilebilir. */
                bulBeni(szFullName, sstring, lineNum);
            }
        }
        else /* dosya ise */
        {
            /* pipe */
        	if (pipe(fd) == -1)
            {
                perror("Failed to create the pipe");
                exit(EXIT_FAILURE);
            }
            
            pid = fork(); /* prosesler oluşturulur */

            /* Error check */
            if(pid == -1)
            {
                perror("Error: Cannot fork \n");
                exit(1);
            }

            /* pid 0 ise child dir. */
            if (pid == 0) 
            {
                printf("\npid:%ld , %s\n",(long)getpid(),szFullName);
                /* Ctrl + C   sinyali yakalanir */
                signal( SIGINT, signalChild );
                /* grep fonksiyonu cagirilarak islemler yaptirilir. */
                grep(szFullName, sstring, fd);
                exit(1); /* exit ile prosesler oldurulur. */
            }
            else /* parent */
            {
                /* childin pipe a yazdigini parent okur */
	       	    close(fd[1]);
    	        while(read(fd[0],bufin,BUFSIZE) > 0)
                {
                    if(countLess == lineNum )
                    {
                        chr = getchar(); /* q ya basilinca program biter */
                        if((chr == 'q')||( chr== 'Q'))
                            exit(1);
                        countLess = 0;
                    }    
    	  	     	printf("%s",bufin);
                    countLess++;
    	  	    }

                /* Sinyal geldiginde if e girer. */
                if (doneflag)
                {
                    /* Pipe yazilanin geri kalaninida okur ve programi bitirir. */
                    close(fd[1]);
                    while(read(fd[0],bufin,BUFSIZE) > 0)
                    {
                        printf("%s",bufin);
                    }
                    printf("\n***** Parent killed. *****\n");
                    exit( doneflag );
                }

                wait(NULL);/* parent child lari bekler. */
            }
        }

    }  /* end while */
    /* Dosyalar kapatilir. */
    while ((closedir(stDirIn) == -1) && (errno == EINTR)) ;

    return 0;
}
Ejemplo n.º 26
0
int _alpm_runscriptlet(alpm_handle_t *handle, const char *filepath,
		const char *script, const char *ver, const char *oldver, int is_archive)
{
	char arg0[64], arg1[3], cmdline[PATH_MAX];
	char *argv[] = { arg0, arg1, cmdline, NULL };
	char *tmpdir, *scriptfn = NULL, *scriptpath;
	int retval = 0;
	size_t len;

	if(_alpm_access(handle, NULL, filepath, R_OK) != 0) {
		_alpm_log(handle, ALPM_LOG_DEBUG, "scriptlet '%s' not found\n", filepath);
		return 0;
	}

	if(!is_archive && !grep(filepath, script)) {
		/* script not found in scriptlet file; we can only short-circuit this early
		 * if it is an actual scriptlet file and not an archive. */
		return 0;
	}

	strcpy(arg0, SCRIPTLET_SHELL);
	strcpy(arg1, "-c");

	/* create a directory in $root/tmp/ for copying/extracting the scriptlet */
	len = strlen(handle->root) + strlen("tmp/alpm_XXXXXX") + 1;
	MALLOC(tmpdir, len, RET_ERR(handle, ALPM_ERR_MEMORY, -1));
	snprintf(tmpdir, len, "%stmp/", handle->root);
	if(access(tmpdir, F_OK) != 0) {
		_alpm_makepath_mode(tmpdir, 01777);
	}
	snprintf(tmpdir, len, "%stmp/alpm_XXXXXX", handle->root);
	if(mkdtemp(tmpdir) == NULL) {
		_alpm_log(handle, ALPM_LOG_ERROR, _("could not create temp directory\n"));
		free(tmpdir);
		return 1;
	}

	/* either extract or copy the scriptlet */
	len += strlen("/.INSTALL");
	MALLOC(scriptfn, len, free(tmpdir); RET_ERR(handle, ALPM_ERR_MEMORY, -1));
	snprintf(scriptfn, len, "%s/.INSTALL", tmpdir);
	if(is_archive) {
		if(_alpm_unpack_single(handle, filepath, tmpdir, ".INSTALL")) {
			retval = 1;
		}
	} else {
		if(_alpm_copyfile(filepath, scriptfn)) {
			_alpm_log(handle, ALPM_LOG_ERROR, _("could not copy tempfile to %s (%s)\n"), scriptfn, strerror(errno));
			retval = 1;
		}
	}
	if(retval == 1) {
		goto cleanup;
	}

	if(is_archive && !grep(scriptfn, script)) {
		/* script not found in extracted scriptlet file */
		goto cleanup;
	}

	/* chop off the root so we can find the tmpdir in the chroot */
	scriptpath = scriptfn + strlen(handle->root) - 1;

	if(oldver) {
		snprintf(cmdline, PATH_MAX, ". %s; %s %s %s",
				scriptpath, script, ver, oldver);
	} else {
		snprintf(cmdline, PATH_MAX, ". %s; %s %s",
				scriptpath, script, ver);
	}

	_alpm_log(handle, ALPM_LOG_DEBUG, "executing \"%s\"\n", cmdline);

	retval = _alpm_run_chroot(handle, SCRIPTLET_SHELL, argv, NULL, NULL);

cleanup:
	if(scriptfn && unlink(scriptfn)) {
		_alpm_log(handle, ALPM_LOG_WARNING,
				_("could not remove %s\n"), scriptfn);
	}
	if(rmdir(tmpdir)) {
		_alpm_log(handle, ALPM_LOG_WARNING,
				_("could not remove tmpdir %s\n"), tmpdir);
	}

	free(scriptfn);
	free(tmpdir);
	return retval;
}
Ejemplo n.º 27
0
int _alpm_runscriptlet(alpm_handle_t *handle, const char *installfn,
                       const char *script, const char *ver, const char *oldver)
{
    char scriptfn[PATH_MAX];
    char cmdline[PATH_MAX];
    char tmpdir[PATH_MAX];
    char *argv[] = { "sh", "-c", cmdline, NULL };
    char *scriptpath;
    int clean_tmpdir = 0;
    int retval = 0;

    if(access(installfn, R_OK)) {
        /* not found */
        _alpm_log(handle, ALPM_LOG_DEBUG, "scriptlet '%s' not found\n", installfn);
        return 0;
    }

    /* creates a directory in $root/tmp/ for copying/extracting the scriptlet */
    snprintf(tmpdir, PATH_MAX, "%stmp/", handle->root);
    if(access(tmpdir, F_OK) != 0) {
        _alpm_makepath_mode(tmpdir, 01777);
    }
    snprintf(tmpdir, PATH_MAX, "%stmp/alpm_XXXXXX", handle->root);
    if(mkdtemp(tmpdir) == NULL) {
        _alpm_log(handle, ALPM_LOG_ERROR, _("could not create temp directory\n"));
        return 1;
    } else {
        clean_tmpdir = 1;
    }

    /* either extract or copy the scriptlet */
    snprintf(scriptfn, PATH_MAX, "%s/.INSTALL", tmpdir);
    if(strcmp(script, "pre_upgrade") == 0 || strcmp(script, "pre_install") == 0) {
        if(_alpm_unpack_single(handle, installfn, tmpdir, ".INSTALL")) {
            retval = 1;
        }
    } else {
        if(_alpm_copyfile(installfn, scriptfn)) {
            _alpm_log(handle, ALPM_LOG_ERROR, _("could not copy tempfile to %s (%s)\n"), scriptfn, strerror(errno));
            retval = 1;
        }
    }
    if(retval == 1) {
        goto cleanup;
    }

    /* chop off the root so we can find the tmpdir in the chroot */
    scriptpath = scriptfn + strlen(handle->root) - 1;

    if(!grep(scriptfn, script)) {
        /* script not found in scriptlet file */
        goto cleanup;
    }

    if(oldver) {
        snprintf(cmdline, PATH_MAX, ". %s; %s %s %s",
                 scriptpath, script, ver, oldver);
    } else {
        snprintf(cmdline, PATH_MAX, ". %s; %s %s",
                 scriptpath, script, ver);
    }

    _alpm_log(handle, ALPM_LOG_DEBUG, "executing \"%s\"\n", cmdline);

    retval = _alpm_run_chroot(handle, "/bin/sh", argv);

cleanup:
    if(clean_tmpdir && _alpm_rmrf(tmpdir)) {
        _alpm_log(handle, ALPM_LOG_WARNING, _("could not remove tmpdir %s\n"), tmpdir);
    }

    return retval;
}
Ejemplo n.º 28
0
int
main(int argc, char **argv)
{
	const char *av = NULL;
	int db;
	int optchar;
	int option_index = 0;

	while ((optchar = getopt_long(argc, argv, "ace:ifgGIlL:noOpPqrstTuvVx", long_options, &option_index)) != EOF) {
		switch (optchar) {
		case 0:
			break;
		case 'a':
			aflag++;
			break;
		case 'c':
			cflag++;
			setcom(optchar);
			break;
		case 'e':
			av = optarg;
			break;
		case 'f':
			fflag++;
			xflag++;
			setcom(optchar);
			break;
		case 'g':
			gflag++;
			setcom(optchar);
			break;
		case 'G':
			Gflag++;
			break;
		case 'i':
			iflag++;
			break;
		case 'I':
			Iflag++;
			setcom(optchar);
			break;
		case 'l':
			lflag++;
			break;
		case 'L':
			file_list = optarg;
			break;
		case 'n':
			nflag++;
			if (optarg) {
				if (!strcmp(optarg, "sort"))
					nofilter |= SORT_FILTER;
				else if (!strcmp(optarg, "path"))
					nofilter |= PATH_FILTER;
			} else {
				nofilter = BOTH_FILTER;
			}
			break;
		case 'o':
			oflag++;
			break;
		case 'O':
			Oflag++;
			break;
		case 'p':
			pflag++;
			setcom(optchar);
			break;
		case 'P':
			Pflag++;
			setcom(optchar);
			break;
		case 'q':
			qflag++;
			setquiet();
			break;
		case 'r':
			rflag++;
			break;
		case 's':
			sflag++;
			break;
		case 't':
			tflag++;
			break;
		case 'T':
			Tflag++;
			break;
		case 'u':
			uflag++;
			setcom(optchar);
			break;
		case 'v':
			vflag++;
			break;
		case 'V':
			Vflag++;
			break;
		case 'x':
			xflag++;
			break;
		case ENCODE_PATH:
			if (strlen(optarg) > 255)
				die("too many encode chars.");
			if (strchr(optarg, '/') || strchr(optarg, '.'))
				die("cannot encode '/' and '.' in the path.");
			set_encode_chars((unsigned char *)optarg);
			break;
		case FROM_HERE:
			{
			char *p = optarg;
			const char *usage = "usage: global --from-here=lineno:path.";

			context_lineno = p;
			while (*p && isdigit(*p))
				p++;
			if (*p != ':')
				die_with_code(2, usage);
			*p++ = '\0';
			if (!*p)
				die_with_code(2, usage);
			context_file = p;
			}
			break;
		case RESULT:
			if (!strcmp(optarg, "ctags-x"))
				format = FORMAT_CTAGS_X;
			else if (!strcmp(optarg, "ctags-xid"))
				format = FORMAT_CTAGS_XID;
			else if (!strcmp(optarg, "ctags"))
				format = FORMAT_CTAGS;
			else if (!strcmp(optarg, "path"))
				format = FORMAT_PATH;
			else if (!strcmp(optarg, "grep"))
				format = FORMAT_GREP;
			else if (!strcmp(optarg, "cscope"))
				format = FORMAT_CSCOPE;
			else
				die_with_code(2, "unknown format type for the --result option.");
			break;
		default:
			usage();
			break;
		}
	}
	if (qflag)
		vflag = 0;
	if (show_help)
		help();

	argc -= optind;
	argv += optind;
	/*
	 * At first, we pickup pattern from -e option. If it is not found
	 * then use argument which is not option.
	 */
	if (!av) {
		av = *argv;
		/*
		 * global -g pattern [files ...]
		 *           av      argv
		 */
		if (gflag && av)
			argv++;
	}
	if (show_version)
		version(av, vflag);
	/*
	 * only -c, -u, -P and -p allows no argument.
	 */
	if (!av) {
		switch (command) {
		case 'c':
		case 'u':
		case 'p':
		case 'P':
			break;
		case 'f':
			if (file_list)
				break;
		default:
			usage();
			break;
		}
	}
	/*
	 * -u and -p cannot have any arguments.
	 */
	if (av) {
		switch (command) {
		case 'u':
		case 'p':
			usage();
		default:
			break;
		}
	}
	if (tflag)
		xflag = 0;
	if (nflag > 1)
		nosource = 1;	/* to keep compatibility */
	if (print0)
		set_print0();
	/*
	 * remove leading blanks.
	 */
	if (!Iflag && !gflag && av)
		for (; *av == ' ' || *av == '\t'; av++)
			;
	if (cflag && av && isregex(av))
		die_with_code(2, "only name char is allowed with -c option.");
	/*
	 * get path of following directories.
	 *	o current directory
	 *	o root of source tree
	 *	o dbpath directory
	 *
	 * if GTAGS not found, getdbpath doesn't return.
	 */
	getdbpath(cwd, root, dbpath, (pflag && vflag));
	/*
	 * print dbpath or rootdir.
	 */
	if (pflag) {
		fprintf(stdout, "%s\n", (rflag) ? root : dbpath);
		exit(0);
	}
	/*
	 * incremental update of tag files.
	 */
	if (uflag) {
		STRBUF	*sb = strbuf_open(0);
		char *gtags = usable("gtags");

		if (!gtags)
			die("gtags command not found.");
		if (chdir(root) < 0)
			die("cannot change directory to '%s'.", root);
		strbuf_puts(sb, gtags);
		strbuf_puts(sb, " -i");
		if (vflag)
			strbuf_putc(sb, 'v');
		strbuf_putc(sb, ' ');
		strbuf_puts(sb, dbpath);
		if (system(strbuf_value(sb)))
			exit(1);
		strbuf_close(sb);
		exit(0);
	}
	/*
	 * complete function name
	 */
	if (cflag) {
		if (Iflag)
			completion_idutils(dbpath, root, av);
		else
			completion(dbpath, root, av);
		exit(0);
	}
	/*
	 * make local prefix.
	 * local prefix must starts with './' and ends with '/'.
	 */
	if (lflag) {
		STRBUF *sb = strbuf_open(0);

		strbuf_putc(sb, '.');
		if (strcmp(root, cwd) != 0) {
			char *p = cwd + strlen(root);
			if (*p != '/')
				strbuf_putc(sb, '/');
			strbuf_puts(sb, p);
		}
		strbuf_putc(sb, '/');
		localprefix = check_strdup(strbuf_value(sb));
		strbuf_close(sb);
#ifdef DEBUG
		fprintf(stderr, "root=%s\n", root);
		fprintf(stderr, "cwd=%s\n", cwd);
		fprintf(stderr, "localprefix=%s\n", localprefix);
#endif
	}
	/*
	 * decide tag type.
	 */
	if (context_file) {
		if (isregex(av))
			die_with_code(2, "regular expression is not allowed with the --from-here option.");
		db = decide_tag_by_context(av, context_file, atoi(context_lineno));
	} else {
		if (rflag && sflag)
			db = GRTAGS + GSYMS;
		else
			db = (rflag) ? GRTAGS : ((sflag) ? GSYMS : GTAGS);
	}
	/*
	 * decide format.
	 * The --result option is given to priority more than the -t and -x option.
	 */
	if (format == 0) {
		if (tflag) { 			/* ctags format */
			format = FORMAT_CTAGS;
		} else if (xflag) {		/* print details */
			format = FORMAT_CTAGS_X;
		} else {			/* print just a file name */
			format = FORMAT_PATH;
		}
	}
	/*
	 * decide path conversion type.
	 */
	if (nofilter & PATH_FILTER)
		type = PATH_THROUGH;
	else if (aflag)
		type = PATH_ABSOLUTE;
	else
		type = PATH_RELATIVE;
	/*
	 * exec lid(idutils).
	 */
	if (Iflag) {
		chdir(root);
		idutils(av, dbpath);
	}
	/*
	 * search pattern (regular expression).
	 */
	else if (gflag) {
		chdir(root);
		grep(av, argv, dbpath);
	}
	/*
	 * locate paths including the pattern.
	 */
	else if (Pflag) {
		chdir(root);
		pathlist(av, dbpath);
	}
	/*
	 * parse source files.
	 */
	else if (fflag) {
		chdir(root);
		parsefile(argv, cwd, root, dbpath, db);
	}
	/*
	 * tag search.
	 */
	else {
		tagsearch(av, cwd, root, dbpath, db);
	}
	return 0;
}
Ejemplo n.º 29
0
void ThermTrace::read_floorplan_mapping() {

    GI(input_file_[0]!=0,!mapping.empty()); // first call read_sesc_variable

    const char *flpSec = SescConf->getCharPtr("","floorplan");
    size_t min = SescConf->getRecordMin(flpSec,"blockDescr");
    size_t max = SescConf->getRecordMax(flpSec,"blockDescr");

    // Floor plan parameters
    for(size_t id=min; id<=max; id++) {
        if (!SescConf->checkCharPtr(flpSec,"blockDescr", id)) {
            MSG("There is a HOLE on the floorplan. This can create problems blockDescr[%lu]", id);
            exit(-1);
            continue;
        }

        const char *blockDescr = SescConf->getCharPtr(flpSec,"blockDescr", id);
        TokenVectorType descr;
        tokenize(blockDescr, descr);

        FLPUnit *xflp = new FLPUnit(strdup(descr[0]));
        xflp->id   = id;
        xflp->area = atof(descr[1])*atof(descr[2]);

        xflp->x       = atof(descr[3]);
        xflp->y       = atof(descr[4]);
        xflp->delta_x = atof(descr[1]);
        xflp->delta_y = atof(descr[2]);

        const char *blockMatch = SescConf->getCharPtr(flpSec,"blockMatch", id);
        tokenize(blockMatch, xflp->match);

        flp.push_back(xflp);
    }

    // Find mappings between variables and flp

    for(size_t id=0; id<flp.size(); id++) {
        for(size_t i=0; i<flp[id]->match.size(); i++) {
            for(size_t j=0; j<mapping.size(); j++) {
                if (grep(mapping[j].name, flp[id]->match[i])) {

#ifdef DEBUG
                    MSG("mapping[%d].map[%d]=%d (%s -> %s)",
                        j, mapping[j].map.size(), id, flp[id]->match[i], mapping[j].name);
#endif

                    I(id < flp.size());
                    flp[id]->units++;
                    I(j < mapping.size());
                    mapping[j].area += flp[id]->area;
                    mapping[j].map.push_back(id);
                }
            }
        }
    }

    for(size_t i=0; i<mapping.size(); i++) {
        for(size_t j=0; j<mapping[i].map.size(); j++) {
            float ratio = flp[mapping[i].map[j]]->area/mapping[i].area;
            mapping[i].ratio.push_back(ratio);
        }
    }

    for(size_t j=0; j<mapping.size(); j++) {
        I(mapping[j].map.size() == mapping[j].ratio.size());
        if (mapping[j].map.empty()) {
            MSG("Error: sesc variable %s [%lu] does not update any block", mapping[j].name, j);
            exit(3);
        }
    }
}
Ejemplo n.º 30
0
/*
 * mainline for grep
 */
int
main(int argc, char **argv)
{
	char	*ap, *test;
	int	c;
	int	fflag = 0;
	int	i, n_pattern = 0, n_file = 0;
	char	**pattern_list = NULL;
	char	**file_list = NULL;

	(void) setlocale(LC_ALL, "");
#if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
#define	TEXT_DOMAIN	"SYS_TEST"	/* Use this only if it weren't */
#endif
	(void) textdomain(TEXT_DOMAIN);

	/*
	 * true if this is running on the multibyte locale
	 */
	mblocale = (MB_CUR_MAX > 1);
	/*
	 * Skip leading slashes
	 */
	cmdname = argv[0];
	if (ap = strrchr(cmdname, '/'))
		cmdname = ap + 1;

	ap = cmdname;
	/*
	 * Detect egrep/fgrep via command name, map to -E and -F options.
	 */
	if (*ap == 'e' || *ap == 'E') {
		regflags |= REG_EXTENDED;
		egrep++;
	} else {
		if (*ap == 'f' || *ap == 'F') {
			fgrep++;
		}
	}

	/* check for non-standard "-line-count" option */
	for (i = 1; i < argc; i++) {
		if (strcmp(argv[i], "--") == 0)
			break;

		if ((argv[i][0] == '-') && isdigit(argv[i][1])) {
			if (strlen(&argv[i][1]) !=
			    strspn(&argv[i][1], "0123456789")) {
				(void) fprintf(stderr, gettext(
				    "%s: Bad number flag\n"), argv[0]);
				usage();
			}

			conalen = conblen = strtoul(&argv[i][1], (char **)NULL,
			    10);

			/* isdigit() check prevents negative arguments */
			if (conalen >= ULONG_MAX) {
				(void) fprintf(stderr, gettext(
				    "%s: Bad context argument\n"), argv[0]);
			}

			if (conalen)
				conflag = CONTEXT;

			while (i < argc) {
				argv[i] = argv[i + 1];
				i++;
			}
			argc--;
		}
	}

	while ((c = getopt(argc, argv, "vwchHilnrbse:f:qxEFIRA:B:C:")) != EOF) {
		unsigned long tval;
		switch (c) {
		case 'v':	/* POSIX: negate matches */
			nvflag = 0;
			break;

		case 'c':	/* POSIX: write count */
			cflag++;
			break;

		case 'i':	/* POSIX: ignore case */
			iflag++;
			regflags |= REG_ICASE;
			break;

		case 'l':	/* POSIX: Write filenames only */
			lflag++;
			break;

		case 'n':	/* POSIX: Write line numbers */
			nflag++;
			break;

		case 'r':	/* Solaris: search recursively */
			rflag++;
			break;

		case 'b':	/* Solaris: Write file block numbers */
			bflag++;
			break;

		case 's':	/* POSIX: No error msgs for files */
			sflag++;
			break;

		case 'e':	/* POSIX: pattern list */
			n_pattern++;
			pattern_list = realloc(pattern_list,
			    sizeof (char *) * n_pattern);
			if (pattern_list == NULL) {
				(void) fprintf(stderr,
				    gettext("%s: out of memory\n"),
				    cmdname);
				exit(2);
			}
			*(pattern_list + n_pattern - 1) = optarg;
			break;

		case 'f':	/* POSIX: pattern file */
			fflag = 1;
			n_file++;
			file_list = realloc(file_list,
			    sizeof (char *) * n_file);
			if (file_list == NULL) {
				(void) fprintf(stderr,
				    gettext("%s: out of memory\n"),
				    cmdname);
				exit(2);
			}
			*(file_list + n_file - 1) = optarg;
			break;

		/* based on options order h or H is set as in GNU grep */
		case 'h':	/* Solaris: supress printing of file name */
			hflag = 1;
			Hflag = 0;
			break;
		/* Solaris: precede every matching with file name */
		case 'H':
			Hflag = 1;
			hflag = 0;
			break;

		case 'q':	/* POSIX: quiet: status only */
			qflag++;
			break;

		case 'w':	/* Solaris: treat pattern as word */
			wflag++;
			break;

		case 'x':	/* POSIX: full line matches */
			xflag++;
			regflags |= REG_ANCHOR;
			break;

		case 'E':	/* POSIX: Extended RE's */
			regflags |= REG_EXTENDED;
			Eflag++;
			break;

		case 'F':	/* POSIX: strings, not RE's */
			Fflag++;
			break;

		case 'R':	/* Solaris: like rflag, but follow symlinks */
			Rflag++;
			rflag++;
			break;

		case 'A':	/* print N lines after each match */
			conalen = strtoul(optarg, &test, 10);
			/* *test will be non-null if optarg is negative */
			if (*test != '\0' || conalen >= ULONG_MAX) {
				(void) fprintf(stderr, gettext(
				    "%s: Bad context argument\n"), argv[0]);
				exit(2);
			}
			if (conalen)
				conflag |= AFTER;
			else
				conflag &= ~AFTER;
			break;
		case 'B':	/* print N lines before each match */
			conblen = strtoul(optarg, &test, 10);
			/* *test will be non-null if optarg is negative */
			if (*test != '\0' || conblen >= ULONG_MAX) {
				(void) fprintf(stderr, gettext(
				    "%s: Bad context argument\n"), argv[0]);
				exit(2);
			}
			if (conblen)
				conflag |= BEFORE;
			else
				conflag &= ~BEFORE;
			break;
		case 'C':	/* print N lines around each match */
			tval = strtoul(optarg, &test, 10);
			/* *test will be non-null if optarg is negative */
			if (*test != '\0' || tval >= ULONG_MAX) {
				(void) fprintf(stderr, gettext(
				    "%s: Bad context argument\n"), argv[0]);
				exit(2);
			}
			if (tval) {
				conflag = CONTEXT;
				conalen = conblen = tval;
			}
			break;

		default:
			usage();
		}
	}
	/*
	 * If we're invoked as egrep or fgrep we need to do some checks
	 */

	if (egrep || fgrep) {
		/*
		 * Use of -E or -F with egrep or fgrep is illegal
		 */
		if (Eflag || Fflag)
			usage();
		/*
		 * Don't allow use of wflag with egrep / fgrep
		 */
		if (wflag)
			usage();
		/*
		 * For Solaris the -s flag is equivalent to XCU -q
		 */
		if (sflag)
			qflag++;
		/*
		 * done with above checks - set the appropriate flags
		 */
		if (egrep)
			Eflag++;
		else			/* Else fgrep */
			Fflag++;
	}

	if (wflag && (Eflag || Fflag)) {
		/*
		 * -w cannot be specified with grep -F
		 */
		usage();
	}

	/*
	 * -E and -F flags are mutually exclusive - check for this
	 */
	if (Eflag && Fflag)
		usage();

	/*
	 * -l overrides -H like in GNU grep
	 */
	if (lflag)
		Hflag = 0;

	/*
	 * -c, -l and -q flags are mutually exclusive
	 * We have -c override -l like in Solaris.
	 * -q overrides -l & -c programmatically in grep() function.
	 */
	if (cflag && lflag)
		lflag = 0;

	argv += optind - 1;
	argc -= optind - 1;

	/*
	 * Now handling -e and -f option
	 */
	if (pattern_list) {
		for (i = 0; i < n_pattern; i++) {
			addpattern(pattern_list[i]);
		}
		free(pattern_list);
	}
	if (file_list) {
		for (i = 0; i < n_file; i++) {
			addfile(file_list[i]);
		}
		free(file_list);
	}

	/*
	 * No -e or -f?  Make sure there is one more arg, use it as the pattern.
	 */
	if (patterns == NULL && !fflag) {
		if (argc < 2)
			usage();
		addpattern(argv[1]);
		argc--;
		argv++;
	}

	/*
	 * If -x flag is not specified or -i flag is specified
	 * with fgrep in a multibyte locale, need to use
	 * the wide character APIs.  Otherwise, byte-oriented
	 * process will be done.
	 */
	use_wchar = Fflag && mblocale && (!xflag || iflag);

	/*
	 * Compile Patterns and also decide if BMG can be used
	 */
	fixpatterns();

	/* Process all files: stdin, or rest of arg list */
	if (argc < 2) {
		matched = grep(0, STDIN_FILENAME);
	} else {
		if (Hflag || (argc > 2 && hflag == 0))
			outfn = 1;	/* Print filename on match line */
		for (argv++; *argv != NULL; argv++) {
			process_path(*argv);
		}
	}
	/*
	 * Return() here is used instead of exit
	 */

	(void) fflush(stdout);

	if (errors)
		return (2);
	return (matched ? 0 : 1);
}