Example #1
0
int main() {
	
	int suc = 0;
	
	if ( pipe(fd1) != 0 || pipe(fd2) != 0 ) {
		printf("PIPES: ERROR AL CREARLAS\n");
		exit(0);		
	};
	
	pid = fork();
	switch(pid) {
		case -1:
			printf("FORK: ERROR\n");
			break;
		case 0:
			hijo();
			break;
		default:
			padre(suc);
			break;
		
	};
	
	exit(0);
};
Example #2
0
File: main.c Project: po8po9/lab
int main(int argc, char **argv){
	int leido,pdesc1[2],pdesc2[2];
	char buff[10000];
	if(pipe(pdesc1) < 0){
		perror("pipe1()");
		return -1;
	}
	if(pipe(pdesc2) < 0){
		perror("pipe2()");
		return -1;
	}
	switch (fork()){
		case 0:
			hijo(pdesc1,pdesc2, argc, argv);
			return 0;
		case -1:
			perror("fork()");
			return -1;
		default:
			break;
	}
	close(pdesc1[0]);
	close(pdesc2[1]);
	memset(buff, 0, sizeof buff); 
	leido = read(0, buff, sizeof buff);
		write(pdesc1[1], buff, sizeof buff);
		leido = read(pdesc2[0], buff, sizeof buff);
		write(1, buff, leido);
	
	close (pdesc1[1]);
	return 0;
}
Example #3
0
int http_worker(int sd_conn, struct sockaddr* addr){

	int dirlen;
	char *droot="tmp";
	char direccion[100];
	bzero(direccion,512);
	char buff[512];
	bzero(buff,512);
	char* tok;
	char* nomArchivo;

	strcat(direccion, droot);
    dirlen = strlen(direccion);
        
    if(direccion[dirlen-1]=='/'){
    	direccion[dirlen-1] = '\0';
    }


	read(sd_conn, buff, sizeof buff);
	write(STDOUT_FILENO, buff, sizeof buff); 
	
	tok = strtok(buff, " ");
		        
	if((strncmp("GET", tok,3))==0){
		nomArchivo = strtok(NULL, " ");
		printf("En el servidor: %s\n\n",direccion);
		                
		hijo(sd_conn, nomArchivo, &direccion[0]);
		                
		printf("\nSALI DEL HIJO\n"); 
	}

	else if(!(strncmp("GET", tok,3))==0){
		
		char *estado;		
		estado = "HTTP/1.1 500 INTERNAL SERVER ERROR\n\nInternal Server error\n";
		write (sd_conn, "HTTP/1.1 500 INTERNAL SERVER ERROR\n\nInternal Server error\n", strlen (estado));
		printf("\nMETODO NO IMPLEMENTADO\n");


	}
	return 0;
}
Example #4
0
	int main(void){

		char *path = "/etc/proyecto_so_1/proy1.ini";
		char *line = NULL;
		size_t len = 0;
		ssize_t reading;
		openlog("ALERT_DAEMON", LOG_PID, LOG_DAEMON);

	 	FILE *fp;

	 	fp = fopen(path,"r");

	 	if (fp == NULL){
			syslog(LOG_ERR,"Fallo en la lectura del archivo de conf proy1.ini");
			closelog();
	    	exit(EXIT_FAILURE);
	      	//notificar por medio de syslog que no se encontro el proy1.ini
	 	}else{
			 	while(!feof(fp)){

	            	while ((reading = getline(&line, &len, fp)) != -1) {

	                	if(line[0] != ';'){

	                  		if(line[0] != '[' && line != NULL){
	                  			//printf("Linea %s\n",line);
	                  			char *buf;
	                  			buf = strsep(&line,"=");

	                  			if((strcmp(buf,"log_tag"))==0){
	                    			tag = strsep(&line,"\0");
	                  	
	                  			}

	                  			if((strcmp(buf,"interval"))==0){
	                    			buf = strsep(&line,"\0");
	                    			interval = atoi(buf);
	                  			
	                  			}
	                		}
	         			}
	       			}
	     		}
		}

		openlog(tag, LOG_PID, LOG_DAEMON);

		if ((lista = (Lista *) malloc (sizeof (Lista))) == NULL){
			syslog(LOG_ERR,"Error, no se pudo inicializar la lista");
	    	exit(EXIT_FAILURE);
	   	}

	   	incializacion(lista);




		while(1==1){

	  		sleep(interval);
	  		char *dir="/var/log";
	  		struct dirent *dp;
	  		DIR *fd;
	  		char  *val,**paragraph;
	  		paragraph = (char**)malloc(1*sizeof(char*));
	  		int position=0;

	  		if ((fd = opendir(dir)) == NULL) {
				
				syslog(LOG_INFO,"Error, no se pudo abrir el directorio /var/log");
	    		closelog();
	    		return;
	  		}

	  		while ((dp = readdir(fd)) != NULL) {

	 			if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
	    		continue;    /* skip self and parent */

	 			char *aux = get_filename_ext(dp->d_name);
	  			// printf("Val--------> %d type dir  %d  type file regular  %d\n ",dp->d_type,DT_DIR,DT_REG);
	   			if(dp->d_type == DT_REG){

	       			if(strcmp(aux,"gz")!=0){
						//agregar a la lista
	        			paragraph = ObtenerPalabras(dp->d_name,paragraph,position);
	        			position++;
	       			}
	   			}
	 		}


					(void) signal(SIGUSR1,manejadorDeSenales);
					int pos=0;

					//printf("Num pal %d\n",position);
					for(pos; pos < position; pos++){

						int i, fds[2];

						if (pipe(fds) == -1) {
							syslog(LOG_ERR,"Error, no se pudo crear la tuberia anonima");
							exit(EXIT_FAILURE);
						}

					 

							pmd5sum = fork();
							if (pmd5sum == 0) {

								hijo(fds,paragraph[pos]);
								kill(pmd5sum,SIGKILL);

							} else if (pmd5sum > 0) {
								/* tratamiento del padre */

					            papa(fds);
					            close(fds[0]);
						        close(fds[1]);
								kill(pmd5sum,SIGKILL);

							} else if (pmd5sum == -1) {

								syslog(LOG_ERR,"Error, fallo en la llamada fork");
								exit(EXIT_FAILURE);

							}

					    	/* tratamiento del padre una vez lanzado su hijo. */
					    	pmd5sum = wait(NULL);

							while (pmd5sum > 0) {
								pmd5sum = wait(NULL);
							}

							if (pmd5sum == -1 && errno != ECHILD) {
								syslog(LOG_ERR,"Error, fallo en la llamada wait");
								exit(EXIT_FAILURE);
							}

					}//fin for que crea hijos
                     // libero el paragragh
                     memset(paragraph,0,sizeof(char*)*position);
					 // visualizacion(lista);
					 // verifico si algun archivo cambio llamando a cambio ?
					char *namepak;
					int cambio = file_change(lista);

					if(cambio==1){//algun archivo cambio
						//procesar .pak
						namepak  = (char*)proccesingPak(lista);
					  	set_change(lista);

					  	pgzip = fork();
					    if (pgzip == 0) {

					          comprimir(namepak);
					          kill(pgzip,SIGKILL);

					    } else if (pgzip > 0) {
					      /* tratamiento del padre */

					    pgzip = wait(NULL);

					    while (pgzip > 0) {
					    	pgzip = wait(NULL);
					 	}


					    }else if (pgzip == -1) {
					    	syslog(LOG_ERR,"Error, fallo en fork");
					      	exit(EXIT_FAILURE);
					    }

					  	if (pgzip == -1 && errno != ECHILD) {
					    	syslog(LOG_ERR,"Error, fallo en wait");
					   		exit(EXIT_FAILURE);
					  	}

					}//FIN IF CAMBIO

	  	}//FIN WHILE TRUE
	}//FIN MAIN
Example #5
0
File: main.c Project: silvi15/proxy
int main (int argc, char *const argv[]){

	/*socket descriptor*/
	int sd;
	int nroproc;
	int longmax = 10;	
	int puerto = 5000;
	int reuse;
	int estado_hijo;

	/* sdtc: socket descriptor totalmente conectado */
	int sdtc;

	/* Definimos la estructura vacia con {}*/
	struct sockaddr_in mi_direccion = {};
	
	/* Creamos un extremo de comunicacion asociado a un descriptor */
	sd = socket (PF_INET, SOCK_STREAM, 0);

	if (sd < 0){
		perror ("error en el socket: ");
		return -1;
	}
	
	if (setsockopt (sd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(int)) == -1){
 		perror ("Error reutilizando puerto");
 		return -1;
	}

	mi_direccion.sin_family = AF_INET;
	mi_direccion.sin_port = htons(puerto);
	mi_direccion.sin_addr.s_addr = INADDR_ANY;

	if ((bind (sd, (struct sockaddr*) &mi_direccion, sizeof (mi_direccion))) < 0){
		perror ("error en bind: ");
		return -1;
	}
	
	if ((listen(sd,longmax))<0){
		perror ("error en listen");
		return -1;
	}

	
	while ((sdtc = accept (sd, NULL, 0)) > 0){	
		
		nroproc = fork ();

		/*codigo del hijo*/
		if (nroproc == 0){
		
			estado_hijo = hijo (sdtc); // funcion crear hijo

			if (estado_hijo != 0){
				perror ("Error en hijo");
				return -1;
			}

			/*hago un return 0 para que tenga vida mientras viva el cliente, dps muere*/
			return 0;

		}

	close (sdtc);
	 	
	}

	return 0;
}
Example #6
0
int main(int args, char *argv[])
{
    /* Variables auxiliares */
    int x,y;
    /* Parseador de Argumentos */
    int opt, req=0;
    /* variables de debug */
    FILE *aux_f=NULL;
    char aux_char[2]={EOF,0};
    /* variables de programa */ 
    ushort sem_array[(N_PARTES*3)+2];
    int n_pro=1,dormir=10,max_t;
    pid_t *pid;
    char clase[]="MAIN";
    int id_shm,id_sem;
    union semun sem_arg;

    /* Cosas de signal */
    hayquesalir=0;
    struct sigaction sa;
    sa.sa_flags=SA_SIGINFO;
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction=manejador;
     

    /*Empieza el programa */

    clock_gettime(CLOCK_REALTIME,&tiempo_inicio);
    debug_file=tmpfile();
    archivo=fopen("input.txt","r");/*TODO*/
    printf("%s: Empieza el programa\n",clase);

    debug1("%s: Empieza el programa",clase);
    debug2("%s: clock_gettime()",clase);
    debug3("%s: %d,%d",clase,(int)tiempo_inicio.tv_sec,
                        -(int)tiempo_inicio.tv_nsec);
    debug2("%s: debug_file=stdout",clase);
    debug2("%s: archivo=",clase);/*TODO*/
    debug2("%s: sigaction(%d)=%d",clase,MYSIGNAL,
        sigaction(MYSIGNAL,&sa,NULL));
    pid=calloc(1,sizeof(pid_t));

    /*  Parseamos los argumentos */
    debug1("%s: Parseamos los argumentos",clase);
    debug2("%s: Hay %d argumento(s)",clase,args-1);
    for(x=0;x<=args-1;x++)
        debug3("%s: arg[%d]: %s",clase,x,argv[x]);
    while ((opt=getopt(args,argv, "D:h:if:s:m:")) != -1){
        debug2("%s: La opcion encontrada es %c",clase,opt);
        switch (opt){
        case 'D':
            debug2("%s: Encontrada opcion para cambiar el "
                                  "archivo de debug",clase);
            debug3("%s: debug_file = %s",clase,optarg);
            aux_f=debug_file;
            debug_file=fopen(optarg,"w");
            aux_char[0]=EOF;
            fwrite(aux_char, sizeof(char),1,aux_f);
            fseek(aux_f,0,SEEK_SET);
            while( EOF != (aux_char[0]=(char)getc(aux_f)))
                fwrite(aux_char,sizeof(char),1,debug_file);
            fclose(aux_f);
            aux_f=stderr;
            debug2("%s: Archivo de debug cambiado",clase);
            break;
        case 'h':
            debug2("%s: Encontrada opcion para cambiar el "
                    "numero de hijos",clase);
            debug3("%s: n_pro=%d",clase,x=atoi(optarg));
            pid=realloc(pid,x*sizeof(pid_t));
            debug2("%s: Reservado un tamaño de memoria %d*%d",
                        clase,(int)x,(int)sizeof(pid_t));
            req|=1;
            n_pro=atoi(optarg);
            debug2("%s: Numero de hijos cambiado",clase);
            break;
        case 'i':
            debug2("%s: Encontrada opcion para tener una e"
                    "ntrada interactiva",clase);
            debug3("%s: -%c",clase,opt);
            req|=4;
            break;
        case 'f':
            debug2("%s: Encontrada opcion para poner un fi"
                    "chero de entrada/salida fisico",clase);
            debug3("%s: %s",clase,optarg);
            req|=2;
            archivo=fopen(optarg,"r");
            debug2("%s: Abierto el fichero de entrada",clase);
            break;
        case 's':
            debug2("%s: Encontrada opcion para tiempo de ejecucion"
                    "del programa",clase);
            debug3("%s: %d a %d",clase,dormir,atoi(optarg));
            dormir=atoi(optarg);
            break;
        
        case 'm':
            debug2("%s: Encontrada opcion para maximo de tiempo que "
                "tiene que esperar",clase);
            max_t=atoi(optarg);
            debug3("%s: max_t=%d",clase,max_t);
            break;
        case ':':
            debug2("%s: En las opciones falta un operando",clase);
            debug3("%s: opt=%c",clase,optopt);
            fprintf(stderr, "La opcion -%c requiere de un operando\n",
                    optopt);
        default:
            debug2("%s: Encontrada opcion no contenida",clase);
            debug3("%s: opt=%c optarg=%s",clase,opt,optarg);
            fprintf(stderr, "Uso: %s [-h num_procesos_hijo -f fichero"
                " de entrada] [-i] [-m tiempo_de_ejec] [-d fichero de"
                " debug]\n", argv[0]);
            debug2("%s: Fallo grave de opciones, salimos del"
                    " programa",clase);
            return -1;
        }
    }
    debug1("%s: Acabamos de parsear las opciones",clase);
    debug2("%s: Comprobamos si hay un archivo al que escribir las trazas"
        ,clase);
    if(aux_f!=stderr){
        aux_f=debug_file;
        aux_char[0]=EOF;
        debug_file=stdout;
        fwrite(aux_char, sizeof(char),1,aux_f);
        fseek(aux_f,0,SEEK_SET);
        while( EOF != (aux_char[0]=(char)fgetc(aux_f)))
            fwrite(aux_char,sizeof(char),1,debug_file);
        fclose(aux_f);
        aux_f=stderr;
    }
    if( (req!=0) && (req==3 || req==7 || req==5) )
    {
        debug2("%s: No se han cumplido las especificaciones de argumentos",
            clase);
        debug3("%s: req=%d",clase,req);
        return -1;
    }


    /* Empezamos con el verdadero programa */
    // Creamos los semaforos
    printf("%s: Intento crear el semaforo\n",clase);
    debug1("%s: Intento crear el semaforo",clase);
    if(-1!=(id_sem=semget(LLAVE,(N_PARTES*3)+2,IPC_CREAT|IPC_EXCL|0666))){
        debug1("%s: El semaforo no existe, lo creo",clase);
        printf("%s: El semaforo no existe, lo creo\n",clase);
        for(x=0;x<(N_PARTES);x++){
            sem_array[x*3]=1;
            sem_array[x*3+SEM_PROD]=1;
            sem_array[x*3+SEM_CONS]=0;
        }
        sem_array[NSEM_PROD]=N_PARTES;
        sem_array[NSEM_CONS]=0;
        sem_arg.array=sem_array;
        semctl(id_sem,0,SETALL,sem_arg);
    }
    else{
        debug1("%s: Como el semaforo exisitia, duermo 1 segundo",clase);
        printf("%s: Como el semaforo exisitia, duermo 1 segundo\n",clase);
        sleep(1);
    }

    printf("%s: Intento crear la memoria compartida\n",clase);
    debug1("%s: Intento crear la memoria compartida",clase);
    // Creamos la memoria compartida
    if(-1!=(id_shm=shmget(LLAVE,SHMTAM,IPC_CREAT|IPC_EXCL|0666))){
        debug1("%s: La memoria compartida no existe, la creo",clase);
        printf("%s: La memoria compartida no existe, la creo\n",clase);
    }


    debug1("%s: Empezamos a crear los hijos",clase);
    for(x=0;x<n_pro&&pid!=0;x++)
    {
        debug1("%s: Creo hijo %d",clase,x);
        pid[x]=fork();
        
        if(pid[x]==0)
        {
            /*TODO problemas entre los dos tipos (stdin) */
            sprintf(clase,"PRO%1d",x+1);
            debug2("%s: He sido creado",clase);
            debug3("%s: CLASE=%s PID=%d",clase,clase,(int)getpid());
            if((req&4)&&(x==(n_pro-1)))
                hijo(clase,max_t,archivo);
            else
                hijo(clase,max_t, stdin);
            //Nunca llegarán hasta aqui, y si llegan:
            exit(EXIT_FAILURE);
        }
    }
   
    /* Despues de lanzar todos los procesos hijo, esperamos */
    sleep(dormir);

    /* Despues de esperar, matamos a todos los procesos hijo */
    for(x=0;x<n_pro;x++)
    {
        kill(pid[x],MYSIGNAL);
        debug2("%s: Mandada señal a tiempo real al proceso hijo %d",
            clase,x);
    }
    for(x=0;x<n_pro;x++){
        debug2("%s: Espero a que acabe un hijo, faltan %d",clase,n_pro-x);
        debug2("%s: Ha salido el hijo de PID %d",clase,wait(&y));
    }

    debug1("%s: Acaba el programa",clase);
    printf("%s: Acaba el programa\n",clase);
    exit(EXIT_SUCCESS);

}
Example #7
0
int main (int argc, char** argv) {
    
    signal(SIGCHLD, childHandler);
    struct stat inodo;
    int father = -1;
    DIR *dirp;
    struct dirent *direntp;
    char *ruta = (char *)malloc(200);
    strcpy(ruta,argv[1]);
    int childpid;
    FD *ph = NULL;
    FD *hp = NULL;
    int rs[2];
    int auxi = 0;
    char **argumentos = (char **) malloc (sizeof(char*)*6);
    char *out = malloc(102400);
    chdir(argv[1]);
    
    hp = (FD*) malloc(sizeof(FD));
    hp->path = malloc(2);
    strcpy(hp->path, "/");
    
    if (stat(ruta, &inodo) == -1 ) {
        fprintf(stderr, "No se pudo aplicar stat sobre el archivo %s: %s \n"
                ,ruta, strerror(errno));
        exit(1);
    }
    if ( !(inodo.st_mode & S_IFDIR) ) {
        fprintf(stderr, "La ruta especificada no es un Directorio\n");
        exit(1);
    }
    
    pipe(rs);
    
directorio:
    
    /**
     *************
     Cable
     *************
     **/
    
    if ( father == 0 ) {
        auxi = hp->pd[0];
    }
    
    
    /**
     ******************************************************
     Imprimimos la Ruta actual y la modificamos para
     que pueda ser interpretada como ruta absoluta
     ******************************************************
     **/
    
    if ( ! (ruta[strlen(ruta)-1] == '/') ){
        strcat(ruta,"/");
    }
    
    if ( (dirp = opendir(ruta)) == NULL ) {
        fprintf(stderr, "No se pudo abrir el directorio\n");
        exit(1);
    }
    
    
    /**
     ****************************************************
     Buscamos en la tabla de inodos del directorio
     ****************************************************
     **/
    
skip:
    while (( direntp = readdir(dirp)) != NULL ) {
        if ('.' == direntp->d_name[0]) {
            goto skip;
        }
        
        /**
         ***********************************************************
         Construccion de la ruta absoluta del subdirectorio
         ***********************************************************
         **/
        
        char *aux = (char *)malloc(strlen(ruta) + strlen(direntp->d_name) + 1);
        strcpy(aux,ruta);
        strcat(aux,direntp->d_name);
        
        
        if (stat(aux, &inodo) == -1 ) {
            fprintf(stderr, "No se pudo aplicar stat sobre el archivo %s: %s \n"
                    ,aux, strerror(errno));
            exit(1);
        }
        else {
            if ( inodo.st_mode & S_IFDIR ) {
                /**
                 ***********************************************************
                 Estructura auxiliar para comunicacion con los hijos
                 ***********************************************************
                 **/
                
                FD *ph_aux = (FD *)malloc(sizeof(FD));
                pipe(ph_aux->pd);
                ph_aux->hijo = malloc(30);
                strcpy(ph_aux->hijo, direntp->d_name);
                ph_aux->sig = ph;
                ph = ph_aux;
                
                if ( (childpid = fork()) == 0 )  {
                    ruta = aux;
                    char *concat = malloc(strlen(ph->hijo)+strlen(hp->path)+3);
                    strcpy(concat, hp->path);
                    strcat(concat, ph->hijo);
                    strcat(concat, "/");
                    
                    if ( father != -1 ) {
                        father = 0;
                        close(hp->pd[0]);	// Cierro la tuberia del abuelo
                        free(hp);			// Libero la estructura copiada del abuelo
                        close(rs[0]);		// Cierro la tuberia de lectura para resultado
                    }
                    
                    father = 0;
                    hp = ph;
                    close(hp->pd[1]);
                    ph = ph->sig;
                    
                    /**
                     *********************************************************
                     Limpieza de la estructura de hijos copiada del padre
                     *********************************************************
                     **/
                    while( !(ph == NULL) ){
                        FD *aux_fd;
                        aux_fd = ph;
                        ph = aux_fd->sig;
                        free(aux_fd);
                    }

                    hp->path = concat;
                    goto directorio;
                    
                }
                else {
                    close(ph->pd[0]);
                    hp->id = childpid;
                }
            }
        }
        free(aux);
    }
    closedir(dirp);
    free(ruta);
    
    
    
    /**
     *****************************************
     Entrada de Comandos
     *****************************************
     **/
    
    
    if ( father == -1 ){
        padre(rs, ph, hp, auxi, argumentos, out, father);
    }
    else {
        hijo(rs, ph, hp, auxi, argumentos, out, father);
    }
    
    FD *aux_fd;
    aux_fd = ph;
    while( !(aux_fd == NULL) ){
        close(aux_fd->pd[1]);
        aux_fd = aux_fd->sig;
        free(ph);
        ph = aux_fd;
    }
    exit(0);
    
}
Example #8
0
int main (int argc, char **argv)
{
  int rstatus;
  pid_t cpid;
  int c;
  int leido;
  int pah[2];
  char buff[500];
  int hap[2];
  
  char pal[100];

  
  if (pipe (pah) == -1)
    {
      perror ("Error al abrir el pipe pah");
      return -1;
    }

  if (pipe (hap) == -1)
  {
      perror ("Error al abrir el pipe hap");
      return -1;
    }

  signal(SIGUSR1, sig1);
  signal(SIGUSR2, sig2);

  while ((c = getopt (argc, argv, "rp:")) != -1)
    switch (c)
      {
      
      case 'r':
	kill(0, SIGUSR1);	
	break;

      case 'p':
	kill(0, SIGUSR2);
	strncpy(pal, optarg, strlen(optarg)+1);
	break;

      default:
	printf("\n No se ingresaron parametros \n");
	return 0;
      }


  while ((leido = read (0, buff, sizeof (buff))) > 0)
    {
      write (pah[1], buff, leido);
    }

  close (pah[1]);

  switch ((cpid = fork ()))
    {
    case 0:
      hijo(pah, hap, pal);
      break;

    case -1:
      perror ("Error en el Fork");
      return -1;
      break;

    default:

      waitpid (cpid, &rstatus, 0);
      printf ("Soy el padre\n");

      while ((leido = read (hap[0], buff, sizeof (buff))) > 0)
	{
	  write (1, buff, leido);
	}
      close (hap[0]);
      close (hap[1]);
      close (pah[0]);
      break;

    }

  return 0;
}