コード例 #1
0
int
main(int argc, char **argv)
{
    int sock, nserver0;
    int errfd;
    pthread_t th;

    pthread_create(&th, NULL, response_to_search, NULL);
    parseArgv(argc, argv);
    if (Daemonize) {
        if (fork()) {
            exit(0);
        }
        else {
            close(2);
            errfd = open(LogFileName, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
            if (errfd < 0) {
                perror("open:");
            }
            close(0);
            close(1);
        }
    }

    initEnv();
    sock = create_daemon_socket(RC_DAEMON_IP_PORT, NBACKLOG);
    if (sock == -1) {
	WARN(0, "create_daemon_socket() failed\n");
	exit(1);
    }
    nserver0 = Nserver;
    while (1) {
        if (Nserver < RC_NSERVERMAX) {
            spawn_server(sock);

            if (nserver0 != Nserver) {
                if (Nserver < RC_NSERVERMAX) {
                    WARN(0, "%d servers active (%d max possible).\n", Nserver, RC_NSERVERMAX);
                }
                else {
                    WARN(0, "%d servers active. reached the limit.\n", Nserver);
                }
            }
        }
        sleep(1);
        nserver0 = Nserver;
    }
    WARN(0, "%s: cannot be reached.\n", __FILE__);

    pthread_join(th, NULL);
    exit(1);
}
コード例 #2
0
///-------------------------------------------------------------
bool CCommandLineParser::parseCommandLine( int argc, const char *const argv[ ] )
///-------------------------------------------------------------
{
    bool isOkay = false;

    if ( true == verifyArgc( argc ) &&
         true == parseArgv(  argv )    )
    {
        isOkay = true;
    }

    return isOkay;
}
コード例 #3
0
ファイル: drain.cpp プロジェクト: AlainRoy/htcondor
int
main( int argc, char *argv[] )
{

	myDistro->Init( argc, argv );

	config();
	dprintf_config_tool_on_error(0);
	dprintf_OnExitDumpOnErrorBuffer(stderr);

	parseArgv( argc, argv );

	DCStartd startd( target, pool );

	if( ! startd.locate() ) {
		fprintf( stderr, "ERROR: %s\n", startd.error() );
		exit( 1 );
	}

	bool rval = false;

	if( cmd == DRAIN_JOBS ) {
		std::string request_id;
		rval = startd.drainJobs( how_fast, resume_on_completion, draining_check_expr, request_id );
		if( rval ) {
			printf("Sent request to drain %s\n",startd.name());
			if (dash_verbose && ! request_id.empty()) { printf("\tRequest id: %s\n", request_id.c_str()); }
		}
	}
	else if( cmd == CANCEL_DRAIN_JOBS ) {
		rval = startd.cancelDrainJobs( cancel_request_id );
		if( rval ) {
			printf("Sent request to cancel draining on %s\n",startd.name());
		}
	}

	if( ! rval ) {
		fprintf( stderr, "Attempt to send %s to startd %s failed\n%s\n",
				 getCommandString(cmd), startd.addr(), startd.error() ); 
		return 1;
	}

	dprintf_SetExitCode(0);
	return 0;
}
コード例 #4
0
ファイル: dscudad.c プロジェクト: Daweek/Original_DSCUDA
int
main(int argc, char **argv)
{
    int sock, nserver0;
    int errfd;

    parseArgv(argc, argv);
    if (Daemonize) {
        if (fork()) {
            exit(0);
        }
        else {
            close(2);
            errfd = open(LogFileName, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
            if (errfd < 0) {
                perror("open:");
            }
            close(0);
            close(1);
        }
    }

    initEnv();
    sock = create_daemon_socket(RC_DAEMON_IP_PORT, NSERVERMAX);
    if (sock == -1) {
	WARN(0, "create_daemon_socket() failed\n");
	exit(1);
    }
    nserver0 = Nserver;
    while (1) {
        if (Nserver < NSERVERMAX) {
            spawn_server(sock);
        }
        else {
            if (nserver0 != Nserver) {
                WARN(0, "already max possible clients (=%d) active.\n", Nserver);
            }
            sleep(1);
        }
        nserver0 = Nserver;
    }
    WARN(0, "%s: cannot be reached.\n", __FILE__);
    exit(1);
}
コード例 #5
0
ファイル: cod_tool.cpp プロジェクト: AlainRoy/htcondor
int
main( int argc, char *argv[] )
{

#ifndef WIN32
	// Ignore SIGPIPE so if we cannot connect to a daemon we do not
	// blowup with a sig 13.
	install_sig_handler(SIGPIPE, SIG_IGN );
#endif

	myDistro->Init( argc, argv );

	config();

	cmd = getCommandFromArgv( argc, argv );
	
	parseArgv( argc, argv );

	DCStartd startd( target, pool ? pool->addr() : NULL );

	if( needs_id ) {
		assert( claim_id );
		startd.setClaimId( claim_id );
	}

	if( ! startd.locate() ) {
		fprintf( stderr, "ERROR: %s\n", startd.error() );
		exit( 1 );
	}

	bool rval = FALSE;
	int irval;
	ClassAd reply;
	ClassAd ad;

	switch( cmd ) {
	case CA_REQUEST_CLAIM:
		fillRequestAd( &ad );
		rval = startd.requestClaim( CLAIM_COD, &ad, &reply, timeout );
		break;
	case CA_ACTIVATE_CLAIM:
		fillActivateAd( &ad );
		irval = startd.activateClaim( &ad, &reply, timeout );
		rval = (irval == OK);
		break;
	case CA_SUSPEND_CLAIM:
		rval = startd.suspendClaim( &reply, timeout );
		break;
	case CA_RESUME_CLAIM:
		rval = startd.resumeClaim( &reply, timeout );
		break;
	case CA_DEACTIVATE_CLAIM:
		rval = startd.deactivateClaim( vacate_type, &reply, timeout );
		break;
	case CA_RELEASE_CLAIM:
		rval = startd.releaseClaim( vacate_type, &reply, timeout );
		break;
	case CA_RENEW_LEASE_FOR_CLAIM:
		rval = startd.renewLeaseForClaim( &reply, timeout );
		break;
	case DELEGATE_GSI_CRED_STARTD:
		irval = startd.delegateX509Proxy( proxy_file, 0, NULL );
		rval = (irval == OK);
		break;
	}

	if( ! rval ) {
		fprintf( stderr, "Attempt to send %s to startd %s failed\n%s\n",
				 getCommandString(cmd), startd.addr(), startd.error() ); 
		return 1;
	}

	printOutput( &reply, &startd );
	return 0;
}
コード例 #6
0
ファイル: main.c プロジェクト: no-ox/PCFAces
int main ( int argc, char *argv[] ) {
  // Loop variables
  int i=0, j=0, k=0, l=0;
  
  // The number of faces and their size depend of the database of faces
  int n=0,m=0; //  size of faces
  int N = 0; // number of faces
  
  char **originFacesPath = NULL; 
  Image *originFaces     = NULL;
  Image *eigenFaces      = NULL;
  Image faceAverage;
  
  // ACP elements :
  // we use array of doubles
  double** R           = NULL; // Matrice d'image (une ligne = un visage)
  double** transposedR = NULL; // Matrice d'image transposée
  double* uR           = NULL; // Vecteur moyen
  double** XXT         = NULL;
  // Eigen elements 
  double* eigenValues    = NULL; // the same for XXT and XTX
  double** eigenVectorsV = NULL; // eigen vectors of XXT
  double** eigenVectorsU = NULL; // eigen vectors of XTX
  
  // Face projetction on the new space
  int q; // dimension of the new space
  double** tabCoefficients  = NULL;
  double** eigenProjections = NULL;
  Image *faceProjections  = NULL;
  
  // Output pictures
  char output[OUTPUT_SIZE];
  
  if(argc <= 1){ 
    fprintf(stderr, "Usage : %s image1 image2 ...\n",argv[0]);
    exit (EXIT_FAILURE);
  }
  N = argc - 1;
  
  originFacesPath = parseArgv(argv,N);
  
  printf("Faces importation... ");
  // Importation des N visages sources (matrix nxm) 
  originFaces = importFaces(originFacesPath,N);
  free(originFacesPath);
  free(originFacesPath[0]);
  originFacesPath = NULL;
  
  n = originFaces[0].nbLignes;
  m = originFaces[0].nbColonnes;
  
  // Conversion des visages en vecteurs lignes dans R
  // (première colonne de la matrice puis seconde etc. = m colonnes qui se suivent de n pixels)
  // R = {I1,I2, ... IN}T avec N le nombre de visages (cela donne une matrice de N * (n*m))
  // Un visage dans R correspond à une ligne 
  R = facesConversion(originFaces,N);
  for(i=0 ; i<N ; i++){
    originFaces[i].t2D = imageDesallocation(originFaces[i].t2D);
  }
  free(originFaces);
  printf("Success!\n");
  
  // If it is a center ACP we have to find the average face uR
  uR = averageFace(R,N,(n*m));
  
  // then, for a center ACP, we transform R in a center matrix : R <- R - uR
  centerFacesMatrix(R,uR,N,(n*m));
  matrixExport(uR,n,m,"averageFace.pgm");
  
  // dim(XXT) = N*N != dim(XTX) = (n*m) * (n*m) [BEAUCOUP]
  // Donc on fait l'ACP sur XXT puis on récupère les composantes principales (CP) de XTX grâce aux formules :
  // va = CP de l'axe a de XXT et ua = CP de l'axe A de XTX
  // ua = va * XT * 1/sqrt(lambdaA) avec lambdaA la valeur propre de l'axe A (eigenValues of XXT are equal to the eigenValues of XTX)
  //     a. XXT
  transposedR = transposeMatrix(R,N,(n*m));
  XXT = multiplyMatrix(R,N,(n*m),transposedR,(n*m),N);
  // R = matrixDesallocation(R);
  
  //     b. Valeurs propres et vecteurs propres
  if((eigenValues = malloc(N*sizeof(double)))==NULL){
    perror("Memory allocation error\n");
    exit(EXIT_FAILURE);
  }
  eigenVectorsV = memoryAllocation(N,N);
  printf("ACP... ");
  acp(XXT,N,eigenValues,eigenVectorsV);
  XXT = matrixDesallocation(XXT);
  
  //    c. Now we have to recovery the principal components of XTX
  eigenVectorsU = memoryAllocation(n*m,n*m);
  
  // /!\ we must consider the number of eigen values != 0
  // There are as many eigen values !=0 in XXT as in XTX
  // but the size of these matrix is different
  // so the loop stop before n*m and even N because here N < n*m
  for(j=0 ; j<N ; j++){
    // we multiply the transposedR matrix by the XXT eigen vector of the jth column.
    for(i=0 ; i<n*m ; i++){
      double sum = 0;
      for(k=0 ; k<N ; k++){
	sum += transposedR[i][k]*eigenVectorsV[k][j];
      }
      eigenVectorsU[i][j]=sum/sqrt(eigenValues[j]);
    }
  }
  free(eigenValues);
  transposedR = matrixDesallocation(transposedR);
  eigenVectorsV = matrixDesallocation(eigenVectorsV);
  
  if  ((eigenFaces = malloc(N*sizeof(Image))) == NULL){
    perror("Memory allocation error\n");
    exit(EXIT_FAILURE);
  }
  for(i=0 ; i< N ; i++){
    eigenFaces[i].nbLignes   = n;
    eigenFaces[i].nbColonnes = m;
    eigenFaces[i].t2D        = imageAllocation(n,m);
  }

  //inverseFacesConversion(eigenFaces,eigenVectorsU,N,n,m);
  for(k=0 ; k<N ; k++){
    for(i=0 ; i<n ; i++){
      for(j=0 ; j<m ; j++){
	// /!\ Why a and b ?! without values are too low
	double a = 110;
	double b = 7000;
	if(k==0)
	  printf("%g\t",eigenVectorsU[j*n+i][k]);
	eigenFaces[k].t2D[i][j] = (Pixel) (abs((int) (a+eigenVectorsU[j*n+i][k]*b)));
      }
      	if(k==0)
	  printf("\n");
    }
  }
  // eigenVectorsU = matrixDesallocation(eigenVectorsU);
  /* for(k=0 ; k<N ; k++){
     sprintf(output,"eigen_faces/eigen_face%d.pgm",k);
     matrixExport(eigenVectorsU[][k],n,m,output);
     }*/
  printf("Success!\n");  
  
  printf("# Writing eigen faces ...\n");
  for(i = 0 ; i < N ; i++){ 
    sprintf(output,"img/eigen_faces/eigen_face%d.pgm",i);
    ecrireImage (eigenFaces[i], output);
  }
  
  // desallocation memoire
  for(i=0 ; i<N ; i++){
    eigenFaces[i].t2D = imageDesallocation(eigenFaces[i].t2D);
  }
  
  printf("# Face projection ...\n");
  // face projection
  q = N - 1;
  // each line contains the coefficients of the face in the new q-dimension-space
  tabCoefficients = memoryAllocation(N,q);
  
  eigenProjections = memoryAllocation(N,n*m);
  for(i=0 ; i<N ; i++){
    projection(R[i], eigenVectorsU, uR, n, m, q, tabCoefficients[i], eigenProjections[i]);
  }
  
  // We search the origin face which is the closest of the face to project
  search_face("img/toProject.pgm", eigenVectorsU, uR, n, m, q, N, tabCoefficients);
  tabCoefficients = matrixDesallocation(tabCoefficients);    
  eigenVectorsU   = matrixDesallocation(eigenVectorsU);
  R               = matrixDesallocation(R);
  free(uR);
  uR = NULL;
  
  // Now we have to create faceProjection with the eigenProjections
  /* if((faceProjections=malloc(N*sizeof(Image)))==NULL){
    perror("Memory allocation error !");
    exit(EXIT_FAILURE);
  }
  for(i=0 ; i< N ; i++){
    faceProjections[i].nbLignes   = n;
    faceProjections[i].nbColonnes = m;
    faceProjections[i].t2D        = imageAllocation(n,m);
  }
  for(k=0 ; k<N ; k++){
    for(i=0 ; i<n ; i++){
      for(j=0 ; j<m ; j++){
	faceProjections[k].t2D[i][j] = (Pixel) eigenProjections[k][j*n+i];
      }
    }
    }*/
  for(i=0 ; i<N ; i++){
    sprintf(output,"projections/projection%d.pgm",i);
    matrixExport(eigenProjections[i],n,m,output);
  }
  eigenProjections = matrixDesallocation(eigenProjections);
  
  /*printf("# Writing projection faces ...\n");
  for(i = 0 ; i < N ; i++){ 
    sprintf(output,"img/projections/projection%d.pgm",i);
    ecrireImage (faceProjections[i], output);
  }
  // Memory desallocation
  for(i=0 ; i<N ; i++){
    faceProjections[i].t2D = imageDesallocation(faceProjections[i].t2D);
    }*/
  
  return EXIT_SUCCESS;
}
コード例 #7
0
ファイル: zfs.c プロジェクト: jamesyan84/zbase
/* Yet !!! main funtion in here */
int main (int argc, char *argv[])
{
    if (RaiseItsPriority ())
	{
	    printf ("Raise it's priority failed.\n");
	}

    memset (&zfs, 0, sizeof (ZFS));
    PZFS pzfs = &zfs;
    /* Parse command line */
    if (parseArgv (pzfs, argc, argv) != 0)
	exit (-1);

	getFileSupport(CONFIG_SUPPORT_FILE, pzfs); //add by Joe
	ZError(DBG_MISC, "pzfs->audioConfig = %d\n", pzfs->audioConfig);
	ZError(DBG_MISC, "pzfs->photoConfig = %d\n", pzfs->photoConfig);
	ZError(DBG_MISC, "pzfs->videoConfig = %d\n", pzfs->videoConfig);

    /* Check, if /data/ImportsummaryDB exists */
    if (fileExists (IMPORT_SUMMARY_DB) == 0)
	{
	    ZError (DBG_MISC, "Will create database->%s", IMPORT_SUMMARY_DB);
	    if (createImportSummaryDB () != 0)
		{
		    ZError (DBG_MISC, "Create database failed.");
		    exit (-1);
		}
	}
    /* initialize zfs */
    if (initZFS (pzfs) != 0)
	exit (-1);
    /* Sync persist data */
    if (getSummary (pzfs) != 0)
	{
	    ZError (DBG_MISC, "Get persist data failed");
	    exit (-1);
	}

    /* Check to see if the DIR_IMPORT and DIR_IMPORTED exists
       NOTE: The zfs will make sure DIR_IMPORTED (/data/AudioLibrary1exists, if it doesn't exists, create it */
    if (fixImportFolder () != 0)
	exit (-1);
    if (fixImportedFolder () != 0)
	exit (-1);
    if (fixExtractedFolder () != 0)
	exit (-1);
    if (fixTmpFolder () != 0)
	exit (-1);

    /* NOTE:Don't give SIGINT signal, just uncommit it when we want debug it */
    //signal(SIGINT, catchKill); /* ctr+c */
    signal (SIGKILL, catchKill);
    signal (SIGTERM, catchKill);

    /* add_inotify_watch to DIR_IMPORT */
    if (addWatchDir (pzfs, DIR_IMPORT) != 0)
	{
	    ZError (DBG_MISC, "Add watch to %s failed", DIR_IMPORT);
	    exit (-1);
	}

    /* Send ide event to zqdevice for our policy */
    zfsSendIdleEvent ();
    /* TCP & UDP */
    ZUtilStartThread (&pzfs->tcpThr, "ZFS_TCP", pzfs, requestThread);
    ZUtilStartThread (&pzfs->udpThr, "ZFS_UDP", pzfs, eventThread);
    /* Watch thread */
    ZUtilStartThread (&pzfs->watchThr, "ZFS_WATCH", pzfs, watchThread);

    //scan import folder on start
    scanImportFolder(pzfs, REMOVE_UNSUPPORTED_FILE);	 


    /* Task thread */
    sleep (2);			/* TBD */
    ZUtilStartThread (&pzfs->taskThr, "ZFS_TASK", pzfs, taskThead);

    /* NOTE: May we can move one thread in here, May be it can cut down spend */
    while (1) {
		#ifdef 		Z_CFG_SMBPRIORITY
	   //	printf ("this is raise smb priority");
		if(pzfs-> b_renice == TRUE)
		{
		//	printf ("raise sma success 222222222222....");
			ZInfo4 (DBG_MISC,"will RaiseItsPriority.");
			if(RaiseSMBPriority() == 0)
			{
				ZInfo4 (DBG_MISC,"RaiseSMBPriority success.");
			}
			else
			{
				ZError (DBG_MISC,"RaiseSMBPriority failed.");
			}
		}
#endif
       sleep (1);
    }
    return 0;
}
コード例 #8
0
ファイル: main.c プロジェクト: nvanheuverzwijn/quicklz
int main(int argc, char* argv[])
{
    input_file = stdin;
    output_file = stdout;
    char *src = 0;
    char *dst = 0;
    size_t input_file_size = 0;
    size_t output_file_size = 0;
    char inputBuffer[1];
    size_t bytesRead = 0;

    parseArgv(argc, argv);

    if(show_help)
    {
        printf("Quicklz implementation version 1:\n");
        printf("\n");
        printf("usage: quicklz [options]:\n");
        printf("\n");
        printf("   -f file - input file that will be compress or decompress. This can be stdin.\n");
        printf("   -h      - show this help message.\n");
        printf("   -o file - output file. This can be stdout.\n");
        printf("   -d      - will decompress the file given via stdin or via -f option.\n");
        printf("\n");
        printf("Examples:.\n");
        printf("\n");
        printf("   cat file.qlz | quicklz -d > file\n");
        printf("   cat file | quicklz > file.qlz\n");
        printf("   quicklz -i file -o file.qlz\n");
        printf("   quicklz -d -i file.qlz -o file\n");

        exit(0);
    }

    do
    {
        bytesRead = fread(
            inputBuffer,
            1,
            1,
            input_file
        );
        char *tmp = (char*)realloc(src, input_file_size + bytesRead);
        if (tmp)
        {
            src = tmp;
            memmove(&src[input_file_size], inputBuffer, bytesRead);
            input_file_size += bytesRead;
        }
        else
        {
            free(src);
            exit(1);
        }
    } while (!feof(input_file));

    if(compress)
    {
        qlz_state_compress *state_compress = (qlz_state_compress *)malloc(sizeof(qlz_state_compress));

        dst = (char*) malloc(input_file_size + 400);
        output_file_size = qlz_compress(src, dst, input_file_size, state_compress);
    }
    else if(decompress)
    {
        qlz_state_decompress *state_decompress = (qlz_state_decompress *)malloc(sizeof(qlz_state_decompress));

        output_file_size = qlz_size_decompressed(src);
        dst = (char*) malloc(output_file_size);

        output_file_size = qlz_decompress(src, dst, state_decompress);
    }

    fwrite(dst, output_file_size, 1, output_file);

    fclose(input_file);
    fclose(output_file);
    return 0;
}
コード例 #9
0
ファイル: main.cpp プロジェクト: svenschmidt75/compiler
int main( int argc, char *argv[] )
{
	//Argumente
	ARGV_STR	argv_str;

	//Meldung ausgeben
	cout << "\nSSLR V" << VERSION << "\n";
	cout << "(c) 2002-2005 by Sven Schmidt\n";
	cout << "[email protected]\n\n";

#ifdef PUBLIC
	//Argumente einlesen
	if( !parseArgv( argc, argv, &argv_str ) )
	{
		//keine Fehler in den Argumenten
		SSLEXScanner	*s;

		//Grammatik-Datei einlesen
		if( readFile( argv[argc - 1] ) < 0 )
			//Fehler
			return( -1 );
#else
	{
		//keine Fehler in den Argumenten
		SSLEXScanner	*s;

		parseArgv( argc, argv, &argv_str );

		//Grammatik-Datei einlesen
//		if( readFile( "/home/sschmidt/Develop/compilerbau/devel/sslr/src/sslr.sslr" ) < 0 )
		if( readFile( "/home/sschmidt/Develop/compilerbau/devel/miniC/miniC.sslr" ) < 0 )
			//Fehler
			return( -1 );
#endif

		//Scanner-Klasse erzeugen
		s = new SSLEXScanner( data, strlen( data ) );

		//Dateinamen des Grammatik-Files aus den Command-Line-Arguments
		SSLRParser	lr( s );
		lr.giveArgs( &argv_str );
		lr.yyParse();

		//Speicher für den Scanner freigeben
		delete( s );

		//Speicher für das Grammatik-File freigeben
		delete[] ( data );
	}

	//Speicher freigeben
	delete[] ( argv_str.name );

	//alles OK
	return EXIT_SUCCESS;
}


int parseArgv( int argc, char *argv[], ARGV_STR *argv_str )
{
	//Argumente parsen
	char	*pos;
	int		i, err = 1, argCnt = 0;

	//mit Standard-Werten initialisieren

	//keine Meldungen
	argv_str->verbose = 0;

	//FIRST-Mengen ausgeben
	argv_str->showFirst = false;

	//FOLLOW-Mengen ausgeben
	argv_str->showFollow = false;

	//Hüllen ausgeben
	argv_str->showHulle = false;

	//Debug-Modus
	argv_str->debug = false;

	//Grammatik-File ausgeben
	argv_str->outputGrammar = false;

	//LALR-Parser
	argv_str->type = SSLR_LALR;

	//Name der Grammatik-Datei
	argv_str->name = new( char[9] );
	strcpy( argv_str->name, "sslr.gra" );

	//Zähler
	i = 1;

	while( i < argc )
	{
		//nun die Argumente lesen
		pos = argv[i++];

		//Schalter?
		if( *pos == '-' )
		{
			//ja, Optionen können von der Art -vd... sein
			pos++;

			while( *pos )
			{
				//welcher Schalter?
				if( *pos == 'v' )
				{
					//Level 1
					argv_str->verbose = 1;

					//höhere Ausführlichkeit?
					if( pos[1] )
					{
						//Zahl auswerten
						if( pos[1] == '0' )
							//keine Meldungen
							argv_str->verbose = 0;

						else if( pos[1] == '1' )
							//Level 1
							argv_str->verbose = 1;

						else if( pos[1] == '2' )
							//Level 2
							argv_str->verbose = 2;

						else
							//Fehlermeldung
							cerr << "sslr: Use -v, -v0, -v1 and -v2!" << endl;

						//Zahl löschen
						pos++;
					}
				}

				else if( !strcmp( pos, "-help" ) )
				{
					//Hilfe ausgeben
					cout << "\n";
					cout << "usage: sslex [OPTIONS]... [GRAMMAR-FILE] ..\n\n";
					cout << "-vX verbose mode (-v0, -v1, -v2)\n";
					cout << "-d generate debug version of cpp-file\n";
					cout << "-f1 output FIRST set\n";
					cout << "-f2 output FOLLOW set\n";
					cout << "-h output closure\n";
					cout << "-o output grammar in BNF form in file sslr.gra\n";
					cout << "-1 generate SLR parser\n";
					cout << "-2 generate LALR parser\n";
					cout << "-3 generate LR parser\n";
					cout << "\n";

					//nächstes Argument
					break;
				}

				else if( *pos == 'd' )
					//Debug-Modus
					argv_str->debug = true;

				else if( !strncmp( "f1", pos, 2 ) )
				{
					//FIRST-Mengen ausgeben
					argv_str->showFirst = true;

					//löschen
					pos++;
				}

				else if( !strncmp( "f2", pos, 2 ) )
				{
					//FOLLOW-Mengen ausgeben
					argv_str->showFollow = true;

					//löschen
					pos++;
				}

				//Hüllen ausgeben?
				else if( *pos == 'h' )
					//Hüllen ausgeben
					argv_str->showHulle = true;

				//Grammatik-Datei ausgeben?
				else if( *pos == 'o' )
					//Grammatik in Datei ausgeben
					argv_str->outputGrammar = true;

				else if( *pos == '1' )
					//SLR-Parser erzeugen
					argv_str->type = SSLR_SLR;

				else if( *pos == '2' )
					//LALR-Parser erzeugen
					argv_str->type = SSLR_LALR;

				else if( *pos == '3' )
					//LR-Parser erzeugen
					argv_str->type = SSLR_LR;

				else
				{
					//unbekannte Option
					cerr << "sslr: Unknown argument line option " << pos << "!\n";
					cerr << "sslr: --help for more Information\n";

					//Fehler
					err++;
				}

				//weiter
				pos++;
			}

			//Argumente zählen
			argCnt++;
		}

		else
			//ist keine Option, muss Grammatik-File sein
			err = 0;
	}

	//kein Grammatik-File angegeben?
	if( err )
		//Fehlt
		cout << "sslr: No grammar file specified!" << endl;

	//etwaige Fehler
	return( err );
}
コード例 #10
-1
ファイル: myshell.c プロジェクト: abhasbodas/LinuxShell
int main(int argc, char **argv)
{
	while(1)	//shell runs till user enters exit
	{
		char * cwd = malloc(256);	//find current working directory for prompt
		assert(cwd != NULL);
		getCurrentDir(cwd);
		printf("\nMyShell:%s$ ", cwd);		//print shell prompt
		free(cwd);

		char *consoleinput = malloc(256);
		assert(consoleinput != NULL);
		//TO DO: Change buffer size to variable

		readCommand(consoleinput);				//accept input
		removeNewLineChar(consoleinput);		//remove '\n' character from input
		removeWhiteSpaces(consoleinput);		//remove all spaces before and after command

		if(strncmp(consoleinput, SUPPORTED_COMMANDS[1], 4) == 0)		//exit
		{
			free(consoleinput);
			printf("\nMyShell Terminated\n");
			return 0;
		}
		else if(strncmp(consoleinput, SUPPORTED_COMMANDS[0], 2) == 0)	//cd
		{
			int result = runChangeDir(consoleinput);
			if(result!=0)
			{
				perror("cd error:");
			}
		}
		else if(strncmp(consoleinput, SUPPORTED_COMMANDS[2], 4) == 0)	//path
		{
			int result = runPath(consoleinput);
			if(result!=0)
			{
				errno = result;
				perror("path error:");
			}
		}
		else
		{
			//handle pipes
			char **commands = parseArgv(consoleinput, SPECIAL_CHARS[4]);	//input destoyed

			int numcommands = 0;

			while( commands[numcommands]!=NULL )
			{
				numcommands++;
			}
			//printf("\nNumber of commands:[%d]", numcommands);

			const int  numpipes = 2*(numcommands-1);
			//printf("\nNumber of pipe file descriptors:[%d]", numpipes);

			/*read and write ends of pipes stay apart by 3
				-increment open pipe indexes by 2 after every command
				-close all pipes
			*/
			
			int pipefds[numpipes];
			
			int i=0;
			for(i=0; i<numpipes;i=i+2)
			{
				pipe(pipefds+i);
			}

			//printf("\npipe() call successful");
			// for(i=0;i<numpipes;i++)
			// {
			// 	printf("[%d]", pipefds[i]);
			// }
			int pipe_w = 1;
			int pipe_r = pipe_w - 3;
			int curcommand = 0;
			
			while(curcommand < numcommands)
			{	
				//printf("\nCommand number:[%d]", curcommand);
				//printf("\ninside pipe loop for command [%s]", commands[curcommand]);

				//Parse Command and Arguments into formatneeded by execv
				char **argv = parseArgv(commands[curcommand], SPECIAL_CHARS[0]);

				//printf("\nCurrent Command:[%s]", argv[0]);
				if(findPath(argv) == 0)
				{
					//executeCommand(argv);
					int child_pid = fork();
					//int child_status;

					if(child_pid < 0)
					{
						//errno = 3;
						perror("fork error:");
					}
					else if(child_pid == 0)		//fork success
					{
						if(pipe_w < numpipes)
						{
							//open write end
							//printf("\nWrite pipe:[%d] to stdout", pipefds[pipe_w]);
							if(dup2(pipefds[pipe_w], 1) < 0)
							{
								perror("pipe write-end error: ");
							}
						}

						if((pipe_r >= 0)&&(pipe_r < numpipes))
						{
							//open read end
							//printf("\nRead pipe:[%d] to stdin", pipefds[pipe_r]);
							if(dup2(pipefds[pipe_r], 0) < 0)
							{
								perror("pipe read-end error: ");
							}
						}

						for(i=0;i<numpipes;i++)	//close off all pipes
						{
							//printf("\nclosing all pipes");
							close(pipefds[i]);
						}

						if(execv(argv[0], argv) == -1)
						{
							perror("Bad command or filename:");
							exit(0);
							//TODO: child hangs here
						}
						//fflush(stdin);
					}		
				}
				else
				{
					printf("\nBad command or filename");
					//TODO: ForkBomb occuring here
					//exit(0);
				}
				free(argv);

				//printf("\nIncrementing pipe ends, moving to next command.");
				curcommand++;
				pipe_w = pipe_w + 2;
				pipe_r = pipe_r + 2;
			}

			//int i=0;
			for(i=0;i<numpipes;i++)	//close off all pipes
			{
				//printf("\nclosing all pipes");
				close(pipefds[i]);
			}

			int status;
			for(i=0;i<numcommands;i++)
			{
				wait(&status);
			}

			free(commands);
		}

		free(consoleinput);
	}
	freeList(pathlist);
}