Пример #1
0
int choice(int sfd,packet* pk,int* fd)
{
		switch(pk->type)
	    {
		case 0:
			get(pk,fd);
			break;
		case 1:
			mycd(pk);
			break;
		case 2:
			myls(pk);
			break;
		case 3:
			myputs(sfd,pk);
			break;
		case 4:
			mygets(pk,fd);
			break;
		case 5:
			myremove(pk);
			break;
		case 6:
			mypwd(pk);
			break;
		case 7:
			getend(fd);
			break;
		default:
			break;
		}
		return 0;
}
Пример #2
0
/*
 *选择:0<往链接写报文>/1<cd>/2<myls>/3<打开文件>/4<读取服务端文件内容并发给客户端>
 *******5<移除文件>/6<获取当前路径>/7<关闭链接>/8<退出循环>
 * */
int choice(node* n,packet* pk,int* running,char *filedir)
{
		switch(pk->type)
		{
				case 0:
						put(pk,n->put_fd);
						break;
				case 1:
						mycd(pk,n->curdir);
						send_pk(n->accept_fd,pk);
						break;
				case 2:
						myls(pk,n->curdir);
						send_pk(n->accept_fd,pk);
						break;
				case 3:
						myputs(pk,&(n->put_fd),filedir);
						send_pk(n->accept_fd,pk);
						break;
				case 4:
						mygets(n->accept_fd,pk,n->curdir);
						break;
				case 5:
						myremove(pk,n->curdir);
						send_pk(n->accept_fd,pk);
						break;
				case 6: 
						mypwd(pk,n->curdir);
						send_pk(n->accept_fd,pk);
						break;
				case 7:
						putend(&(n->put_fd));
						break;
				case 8:
						*running=0;
						break;
				default:break;
		}
		return 0;
}
Пример #3
0
main(int argc, char *argv[ ])
{
       //*Lab 5 CODE
  char *tok;
  char cmdArgs[2][MAX] = {'\0'};
  char cwd[128];
  int cmdCount = 0;
       //LAB 5 CODE*
  char temp[MAX];

  int n;
  char line[MAX], ans[MAX];

       //*Lab 5 CODE
  getcwd(cwd, 128);   // get CWD pathname
       // Lab 5 CODE*
  printf("cwd: %s\n", cwd);

  if (argc < 3){
     printf("Usage : client ServerName ServerPort\n");
     exit(1);
  }

  client_init(argv);
  // sock <---> server
  printf("********  processing loop  *********\n");
  while (1){
    //printf("input two numbers to add : ");
    //bzero(line, MAX);                // zero out line[ ]

          // *LAB 5 CODE
    cmdCount = 0;
    strcpy(cmdArgs[0],"");
    strcpy(cmdArgs[1],"");
    
    printf("Input a command: ");    
          // LAB 5 CODE*

    fgets(line, MAX, stdin);         // get a line (end with \n) from stdin
    //printf("line: %s\n", line);
    line[strlen(line)-1] = 0;        // kill \n at end
    //printf("line[0]: %c\n", line[0]);
    //if(line[0]==0)                  // exit if NULL line
       //{exit(0);}

         // *Lab 5 CODE
    strcpy(temp, line);
    //printf("temp: %s\n", temp);
    
    tok = strtok(line, " ");
    cmdCount++;
    //printf("temp: %s\n", temp);
    //printf("cmdArgs[0] = %s\n", cmdArgs[0]);
    //printf("cmdCount: %d\n", cmdCount);
    while(tok != NULL)
    {
      strcpy(cmdArgs[cmdCount-1], tok);
      tok = strtok(NULL, " ");
      cmdCount++;
      //printf("cmdCount: %d\n", cmdCount);
    }
    //printf("cmdCount: %d\n", cmdCount);
    //printf("line: %s\n", line);
    //printf("cmdArgs[0] = %s\n", cmdArgs[0]);
    if(strcmp(cmdArgs[0], "lcat") == 0) 
    {
      if(strcmp(cmdArgs[1],"") != 0) {mycat(cmdArgs[1]);}
      else {printf("ERROR: pathname not given");}
    }
    else if (strcmp(cmdArgs[0], "lpwd") == 0) 
    {
      mypwd(cwd);
    }
    else if (strcmp(cmdArgs[0], "lls") == 0) 
    {
      printf("args: %s\n", cmdArgs[1]);
      if(strcmp(cmdArgs[1],"") != 0) {myls(cmdArgs[1]);}
      else 
      {
        printf("cwd: %s\n", cwd);
        myls(cwd);
      }
    }
    else if (strcmp(cmdArgs[0], "lcd") == 0) 
    {
      if(strcmp(cmdArgs[1],"") != 0) {mycd(cmdArgs[1]);}
      else {mycd(cwd);}
    }
    else if (strcmp(cmdArgs[0], "lmkdir") == 0) 
    {
      if(strcmp(cmdArgs[1],"") != 0) {mymkdir(cmdArgs[1]);}
      else {printf("ERROR: pathname not given");}
    }
    else if (strcmp(cmdArgs[0], "lrmdir") == 0) 
    {
      if(strcmp(cmdArgs[1],"") != 0) {myrmdir(cmdArgs[1]);}
      else {printf("ERROR: pathname not given");}
    }
    else if (strcmp(cmdArgs[0], "lrm") == 0) 
    {
      if(strcmp(cmdArgs[1],"") != 0) {myrm(cmdArgs[1]);}
      else {printf("ERROR: pathname not given");}
    }
    else if (strcmp(cmdArgs[0], "get") == 0) 
    {
      if(strcmp(cmdArgs[1],"") != 0) {mycp(cmdArgs[1], cwd);}
      else {printf("ERROR: pathname not given");}
    }
    else if (strcmp(cmdArgs[0], "quit") == 0) 
    {
      printf("Goodbye!\n");
      return 0;
    }
    else // Not a local command, work with the sever
    {
      // Send command to server
      n = write(server_sock, temp, MAX);
      printf("client: wrote n=%d bytes; line=(%s)\n", n, temp);
      // Send command pathname
      //n = write(server_sock, cmdArgs[0], MAX);
      //printf("client: wrote n=%d bytes; line=(%s)\n", n, line);

      // Now read the Reply and Results in from the Server...

      //REPLY
      //n = read(server_sock, ans, MAX);
      //printf("client: read  n=%d bytes; echo=(%s)\n",n, ans);

      //RESULTS
      //n = read(server_sock, ans, MAX);
      //printf("client: read  n=%d bytes; echo=(%s)\n",n, ans);

      readData(ans);
    }
         // Lab 5 CODE*

    //
    // Send ENTIRE line to server
    //n = write(server_sock, line, MAX);
    //printf("client: wrote n=%d bytes; line=(%s)\n", n, line);

    // Read a line from sock and show it
    //n = read(server_sock, ans, MAX);
    //printf("client: read  n=%d bytes; echo=(%s)\n",n, ans);
  }
}
Пример #4
0
int callInternal(command* C, char* homeDir)
{
	if (C->argc == 0)
		return 0;
	else if (strcmp(C->argv[0],"exit") == 0)
		return 1;
	else if (strcmp(C->argv[0],"mycat") == 0)
	{
		if (C->argc == 2)
			mycat(C->argv[1]);
		else if (C->argc == 1)
			printf("Argument missing\n");
		else if (C->argc > 2)
			printf("Incorrect usage of mycat\n");
	}
	else if (strcmp(C->argv[0],"mycp") == 0)
	{
		if (C->argc == 3)
			mycp(C->argv[1],C->argv[2]);
		else if (C->argc == 2)
			printf("Destination needed\n");
		else if (C->argc == 1)
			printf("Source & destination needed\n");
		else
			printf("Incorrect usage of mycp\n");
	}
	else if (strcmp(C->argv[0],"mypwd") == 0)
	{
		if (C->argc > 1)
			printf("Incorrect usage of mypwd\n");
		else
		{		
			char* pwd = mypwd();
			printf("%s\n",pwd);
			free(pwd);
		}
	}
	else if (strcmp(C->argv[0],"mymkdir") == 0)
	{
		if (C->argc < 2)
			printf("missing argument\n");
		else if (C->argc > 2)
			printf("Incorrect usage of mymkdir\n");
		else
			mymkdir(C->argv[1]);
	}
	else if (strcmp(C->argv[0],"myrmdir") == 0)
	{
		if (C->argc < 2)
			printf("missing argument\n");
		else if (C->argc > 2)
			printf("Incorrect usage of mymkdir\n");
		else
			myrmdir(C->argv[1]);	
	}
	else if (strcmp(C->argv[0],"mycd") == 0)
	{
		if (C->argc >2)
			printf("Incorrect usage of mycd\n");
		else if (C->argc == 2)
			mycd(C->argv[1]);
		else
			mycd(homeDir);
	}
	else if (strcmp(C->argv[0],"myls") == 0)
	{
		if (C->argc == 1)
			myls(NULL,0);
		else if (C->argc == 2)
			if (strcmp(C->argv[1],"-l") == 0)
				myls(NULL,1);
			else
				myls(C->argv[1],0);
		else if (C->argc == 3)
			if (strcmp(C->argv[1],"-l") == 0)
				myls(C->argv[2],1);
			else
			printf("Incorrect usage of myls\n");
		else
			printf("Incorrect usage of myls\n");
	}
	else if (strcmp(C->argv[0],"myrm") == 0)
	{
		if (C->argc == 2)
			myrm(C->argv[1]);
		else if (C->argc == 1)
			printf("missing argument\n");
		else
			printf("Incorrect usage of myrm\n");
	}
	else
		printf("command not found: %s\n",C->argv[0]);
	return 0;
}
Пример #5
0
int main(int argc, char** argv)
{
	int count=0, i=0, cmp, j, valid=0;
	char key[MAX];
	
	//run the shell till user inputs 'quit' or Ctrl-C
	while(strcmp(cmdline, "quit") != 0)
	{
		count = 0;
		
		//our shell's prompt
		printf("afreen@myShell $ ");
		//get command line input
		gets(cmdline);
		
		//tokenize the CL input delimited by " " using strtok() into args
		args[count++] = strtok(cmdline, " ");
		
		//tokenize the entire string till the next token encountered
		//does not have a NULL pointer
		while((args[count++] = strtok(NULL, " ")));
		count--;		//no of arguments (argc)
		
		//if user wants to clear screen
		if(strcmp(args[0], "clear") == 0)
		{
			myclear();
		}
		
		//checking for the input command
		strcpy(key, args[0]);
		for(i=0; i<18; i++)	//look through our check array for command
		{
		  if(strcmp(check[i], key) == 0)
		  {
		      valid = -1;
		      switch(i)
		      {
		        case 0:   mycat(count, args);
		                  break;
		        
		        case 1:   mycd(count, args);
		                  break;
          
		        case 2:   mycp(count, args);
		                  break;
		         
		        case 3:   mydate(count, args);
		                  break;
		          
		        case 4:   myhead(count, args);
		                  break;
		                  
		        case 5:   myls(count, args);
		                  break;
		                  
		        case 6:   myll(count, args);
		                  break;
		                  
		        case 7:   myln(count, args);
		                  break;
		                  
		        case 8:   myld(count, args);
		                  break;
		                  
		        case 9:   mymkdir(count, args);
		                  break;
		                  
		        case 10:  mymv(count, args);
		                  break;
		                  
		        case 11:  mypwd(count, args);
		                  break;
		                  
		        case 12:  myrm(count, args);
		                  break;
		                  
		        case 13:  myrmdir(count, args);
		                  break;
		                  
		        case 14:  mytail(count, args);
		                  break;
		                  
		        case 15:  mytime(count, args);
		                  break;
		                  
		        case 16:  mytouch(count, args);
		                  break;
		                  
		        case 17:  myuname(count, args);
		                  break;
		                  		        
		        default: printf("%s: Command not found\n", key);
		    		  break;
		      }	
		      break;  
		  }
		}
		
		
  	}
  	return 0;
}
Пример #6
0
int main(void) {

	char buf[1024];
	int i;
	pid_t pid;
	int ** tuberias;
	int pids;
	// Guardar entradas estandar para posible redireccion
	int rEntrada = dup(fileno(stdin));
	int rSalida = dup(fileno(stdout));
	int rError = dup(fileno(stderr));
	
	/* Señales, se tratan inmediatamente SIGINT == Ctrl+C y SIGQUIT == Ctrl + \ */
	// Ignoramos las señales
	signal(SIGINT , SIG_IGN);
	signal(SIGQUIT, SIG_IGN);
	
	printf("msh> ");
	
	while (fgets(buf, 1024, stdin)) {
		
		// Si hago background poner esto tambien, ignorar como en la minishell 
		signal(SIGINT,SIG_IGN);
		signal(SIGQUIT,SIG_IGN);
		
		// Acceso al atributo de un puntero de forma sencilla -> 

		line = tokenize(buf);		
		int status;


		if (line==NULL) {
			continue;
		}

		if (line->redirect_input != NULL) {
			funcionRedireccion ( line->redirect_input , NULL , NULL ); 
		}
		if (line->redirect_output != NULL) {
			funcionRedireccion ( NULL , line->redirect_output , NULL ); 
		}
		if (line->redirect_error != NULL) {
			funcionRedireccion ( NULL , NULL , line->redirect_error ); 
		}
		if (line->background) {
			printf("comando a ejecutarse en background\n");
			return(1);
		} 

		// int execvp (const char *file , char *const argv[]); 

		// Para 1 solo comando, contampla CD 
		if(line->ncommands==1){
			
			//Señales, accion por defecto
			signal(SIGINT , SIG_DFL);
			signal(SIGQUIT, SIG_DFL);
			
			// Comprueba si es cd
			if (strcmp(line->commands[0].argv[0], CDCONTS) == 0){// Comprueba si es el mandato es cd, llama a subprograma
				mycd();
			}else{ // Ejecuta el comando, como ejercicio de ejecuta del tema 3 
				pid = fork();
				if (pid < 0) {  // Error fork
					fprintf(stderr, "Falló el fork().\n%s\n", strerror(errno));
					exit(1);
				}
				else if (pid == 0) { // Hace hijo 
					
					if(ComandoValido(line->commands[0].filename)==0){ // Mirar si es un comando Válido
					
						execvp(line->commands[0].filename, line->commands[0].argv ); // Si pasa del exec , es que hay error
						// devuelve - 1 y salta el error 
						fprintf(stderr, "Error al ejecutar el comando: %s\n", strerror(errno));
						// exit(1); lo quito para seguir con el prompt
						
					} else {
						fprintf(stderr, "%s : No se encuentra el mandato\n" , line->commands[0].argv[0]); // El comando no es válido, mostrarlo
					}					
				}else{ 	
					wait (&status);
					if (WIFEXITED(status) != 0)
						if (WEXITSTATUS(status) != 0)
							printf("El comando no se ejecutó correctamente\n");
				}
			}
			
		}else if(!(line->ncommands == 1)){ // Si son 2 comandos o más
				
			// Variable tuberia de memoria dinamica para los N-1 comandos que haya ( una tuberia cada 2 comandos )
			// Variable pid para los descriptores de fichero, irá cambiando con los forks 
				
			tuberias=(int**) malloc ((line->ncommands-1)*sizeof(int*)); 
			for(i=0;i<line->ncommands-1;i++){
				tuberias[i]=(int*)malloc(2*sizeof(int));
				pipe(tuberias[i]);
			}
			
			for(i=0;i<line->ncommands;i++){
				
				//Señales, accion por defecto
				signal(SIGINT , SIG_DFL);
				signal(SIGQUIT, SIG_DFL);
				
				if(ComandoValido(line->commands[i].filename)==0){ // Si todos los comandos son validos
				
					// Hace un fork() para cada hijo. El numero va cambiando con los forks
					pids=fork();				
					if(pids<0){ //Error fork
						fprintf(stderr, "Falló el fork().\n%s\n", strerror(errno));
						exit(1);
					} else if (pids==0){ // Sino error hace hijos

						if(i==0){ //Primer hjijo
							close(tuberias[i][0]);
							dup2(tuberias[i][1],1);
							execvp(line->commands[i].argv[0], line->commands[i].argv);

							fprintf(stderr, "Error al ejecutar el comando: %s\n", strerror(errno));
							exit(1);
							
						}else if(i==(line->ncommands-1)){	// Utimo hijo
							close(tuberias[i-1][1]);
							dup2(tuberias[i-1][0],0);
							execvp(line->commands[i].argv[0], line->commands[i].argv);

							fprintf(stderr, "Error al ejecutar el comando: %s\n", strerror(errno));
							exit(1);
							
						}else{	// Resto de hijos			
							close(tuberias[i][0]);	
							close(tuberias[i-1][1]);	
							dup2(tuberias[i-1][0],0);	
							dup2(tuberias[i][1],1);

							execvp(line->commands[i].argv[0], line->commands[i].argv);	

							fprintf(stderr, "Error al ejecutar el comando: %s\n", strerror(errno));
							exit(1);
							
						}

					}else{	//Padre
						if(!(i==(line->ncommands-1))){ // Por esto la violacion del core
							close(tuberias[i][1]);
						}
					}
				}else { // Si hay comandos no validos 
					fprintf(stderr, "%s : No se encuentra el mandato\n" , line->commands[i].argv[0]); // El comando no es válido, mostrarlo
				}		
			}
			// Esperar que termine todo, 0 significa esperar a cualquier proceso hijo
			waitpid(pids,&status,0); 
			
			//Liberamos la memoria reservada antes
			for(i=0;i<line->ncommands-1;i++){
				free(tuberias[i]);
			}
			free(tuberias);
			
		}
		
		// Restablecer las redirecciones
		
		if(line->redirect_input != NULL ){
			dup2(rEntrada , fileno(stdin));	
		}
		if(line->redirect_output != NULL ){
			dup2(rSalida , fileno(stdout));	
		}
		if(line->redirect_error != NULL ){
			dup2(rError , fileno(stderr));	
		}
		
		printf("msh> ");
	}
	return 0;
	
}
Пример #7
0
int SMASHexec(char ** command){
	int status;
	//printf("Hi\n");
	if (0==strcmp("exit", command[0])){
		free(line);
		free(args);
		exit(0);
	} else if (0==strcmp("myinfo", command[0])){
		myinfo();
	} else if (0==strcmp("cd", command[0]) && NULL == args[1]) {
		char * HOME="";
		HOME = getenv("HOME");
		if (NULL != HOME){
			chdir(HOME);
		} else{
			printf("$HOME path corrupt\n");
		}
		
	}else if (0 == strcmp("cd", command[0])){
		mycd(command[1]);
	}else {
		
		if (pipe_flag){
			args[pipe_index]=NULL;
			//pid_t child2;
			int fds[2];
			int buffersize = arglen - pipe_index -1;
			//printf("%d\n", buffersize );
			char ** buffer = calloc(sizeof(char*), buffersize);
			for (int i = 1; i <= buffersize; ++i)
			{
				buffer[i-1] = command[pipe_index + i];
				//printf("ABC%s\n", buffer[i-1] );
			}
			//printf("%s\n", buffer[0] );
			pipe(fds);
			//child = fork();
			if (fork() == 0){
				dup2(fds[0], STDIN_FILENO);
				//close(fds[1]);
				close(fds[0]);
				//child2 = fork();
				if (fork() == 0){
					dup2(fds[1], STDOUT_FILENO);
					close(fds[0]);
					//close(fds[1]);
					//printf("1st %s\n", command[0] );
					execvp(command[0], command);
					
				}
				wait(NULL);
				close(fds[1]);
				execvp(buffer[0], buffer);
			}
			close(fds[1]);
			close(fds[0]);
			free(buffer);
			wait(NULL);		
		} else {
			//printf("B\n");
			child = fork();
			if (child){
			//parent
				if (0==strcmp(command[arglen-1], "&")){
					char buff[PATH_MAX + 1];
					char * cpath;
					cpath = getcwd(buff, PATH_MAX+1);
					printf("\n< %s SMASH >$ ", cpath);
					waitpid(-1, &status, WNOHANG );
				} else {
					waitpid(child, &status, 0 );
				}

			} else{
			//child
			//sleep(5); used for testing of sigint handler
				redirect(args);
				if (redirect_flag){
					if ( redirect_flag == 1 ){
						args[input_redirect_index]=NULL;
					} else if ( redirect_flag == 2 ){
						args[output_redirect_index]=NULL;
					} else if ( redirect_flag == 3){
						args[output_redirect_index]=NULL;
						args[input_redirect_index]=NULL;
					}

				}
				int failure = execvp(command[0], command);
				if (-1 == failure){
					perror("SMASH");
					exit(EXIT_FAILURE);
				}
			}
		}
	}
	return child;
}