示例#1
0
文件: shellex.c 项目: 09zwcbupt/csapp
/* eval - Evaluate a command line */
void eval(char *cmdline) 
{
    char *argv[MAXARGS]; /* Argument list execve() */
    char buf[MAXLINE];   /* Holds modified command line */
    int bg;              /* Should the job run in bg or fg? */
    pid_t pid;           /* Process id */
    
    strcpy(buf, cmdline);
    bg = parseline(buf, argv); 
    if (argv[0] == NULL)  
	return;   /* Ignore empty lines */

    if (!builtin_command(argv)) { 
	if ((pid = Fork()) == 0) {   /* Child runs user job */
	    if (execve(argv[0], argv, environ) < 0) {
		printf("%s: Command not found.\n", argv[0]);
		exit(0);
	    }
	}

	/* Parent waits for foreground job to terminate */
	if (!bg) {
	    int status;
	    if (waitpid(pid, &status, 0) < 0)
		unix_error("waitfg: waitpid error");
	}
	else
	    printf("%d %s", pid, cmdline);
    }
    return;
}
示例#2
0
文件: rshell.c 项目: czn73126/rshell
void proc(void)
{
    int status,i;
    char *command = NULL;
    char **parameters;
	char prompt[MAX_PROMPT];
    parameters = malloc(sizeof(char *)*(MAXARG+2));
    buffer = malloc(sizeof(char) * MAXLINE);
    if(parameters == NULL || buffer == NULL)
    {
        printf("Rshell error:malloc failed.\n");
        return;
    }
	//arg[0] is command
	//arg[MAXARG+1] is NULL
    while(TRUE)
    {
        type_prompt(prompt);
        if(-1 == read_command(&command,parameters,prompt))
			continue;
		if(builtin_command(command,parameters))
			continue;
        if(fork()!=0)
        {
            waitpid(-1,&status,0);
        }
        else
        {
            execvp(command,parameters);
        }
    }
}
示例#3
0
void eval(char *cmdline) {
    char *argv[MAXARGS];    // argv pour exec
    char buf[MAXLINE];      // contient ligne commande modifiee
    char buf2[MAXLINE];     // pour les substitutions de jobid
                            // par pid pour la commande kill
    strcpy(buf, cmdline);
    bool bg = parseline(buf, argv);

    if (!builtin_command(argv) && replace_kill_jobs(buf2, argv)) {
        int pid;
        if ((pid = Fork()) == 0) {
            exec_command(argv); // Ne retourne jamais
        }

        jobid_t jobid = jobs_add(pid, cmdline);
        if (jobid == INVALID_JOBID) {
            printf("Error while trying to register job with pid %d ", pid);
            printf("Maximum number of jobs (%d) reached ?)\n", MAXJOBS);
        }

        if (bg) {
            job_print_with_pid(jobid);
        }
        else {
            job_fg_wait(jobid, false);
        }
    }

    jobs_print_update();
    exit_forget_next_forced();
}
示例#4
0
/* eval - Evaluate a command line */
void eval(char *cmdline) 
{

    char *argv[MAXARGS]; /* Argument list execve() */
    char buf[MAXLINE];   /* Holds modified command line */
    int bg;              /* Should the job run in bg or fg? */
    pid_t pid;           /* Process id */

    signal(SIGCHLD, reaperthegrim);
    strcpy(buf, cmdline);
        bg = parseline(buf, argv);  
    //bg = p3parseline(buf, argv); /* call new parseline function for cs485 project 3 */
    if (argv[0] == NULL)  
	return;   /* Ignore empty lines */
    
    if (!builtin_command(argv)) { 
	if ((pid = fork()) == 0) {   /* Child runs user job */
	    if (execve(argv[0], argv, environ) < 0) {
		printf("%s: Command not found.\n", argv[0]);
		exit(0);
	    }
	}

	/* Parent waits for foreground job to terminate */
	if (!bg) {
	    int status;
	    if (waitpid(pid, &status, 0) < 0)
		unix_error("waitfg: waitpid error");
	}
	else{
	    printf("%d %s", pid, cmdline);
	    int i =0;
	    int ctr = 1;
	    while(ctr==1)
                {
			//puts the pid into the PIDS array so we can keep track of all pids
                        if(PIDS[i]==0)
                        {
                                PIDS[i]=pid;
                                ctr=0;
			}
                        else
                        {
                                i++;
                        }
                }
	   }
         }

    in = 0;
    out = 0;
    inpos = 0;
    outpos = 0;
    
    return;
}
示例#5
0
/*
 * Executes command while processing call tree   
 * parameters: char** args - command arguments
 * returns: exit status of command executed
 */
static int execCommand(char** args)
{
    int rv = 0;//return exit status
    int execute(char**);//execute() function declaration
    int builtin_command(char**,int*);//built in handler function declaration 
    
    if ( !builtin_command(args,&rv) )//handles built in command
        rv = execute(args);//regular command
    return rv;//returns exit status of command executed
}
示例#6
0
/*
 * eval - Evaluate the command line that the user has just typed in
 *
 * If the user has requested a built-in command (quit, jobs, bg or fg)
 * then execute it immediately. Otherwise, fork a child process and
 * run the job in the context of the child. If the job is running in
 * the foreground, wait for it to terminate and then return.  Note:
 * each child process must have a unique process group ID so that our
 * background children don't receive SIGINT (SIGTSTP) from the kernel
 * when we type ctrl-c (ctrl-z) at the keyboard.
 */
void
eval(char *cmdline)
{
    int bg;              /* should the job run in bg or fg? */
    struct cmdline_tokens tok;
    sigset_t prev, mask_all;
    int state;
    pid_t pid;
    struct job_t *job_ins;

    /* Parse command line */
    bg = parseline(cmdline, &tok);

    if (bg == -1) /* parsing error */
        return;
    if (tok.argv[0] == NULL) /* ignore empty lines */
        return;

    /* Fig. 8.40 */
    if (!builtin_command(&tok)) {
        Sigemptyset(&mask_all);
        Sigaddset(&mask_all, SIGCHLD);
        Sigaddset(&mask_all, SIGINT);
        Sigaddset(&mask_all, SIGTSTP);
        Sigprocmask(SIG_BLOCK, &mask_all, &prev); /* Block at beginning */

        if ((pid = Fork()) == 0) { /* Child process */
            Sigprocmask(SIG_SETMASK, &prev, NULL); /* Unblock inside child */
	    Setpgid(0, 0); /* one proc and shell in pgrp */

	    open_dup2_in(tok.infile);
	    open_dup2_out(tok.outfile);
	    if (execve(tok.argv[0], tok.argv, environ) < 0) {
	        printf("%s: Command not found.\n", tok.argv[0]);
	        exit(0);
	    }
	}

        /* Parent process */

        state = bg ? BG : FG;
        addjob(job_list, pid, state, cmdline);
        job_ins = getjobpid(job_list, pid);

        Sigprocmask(SIG_SETMASK, &prev, NULL); /* Unblock 3 signals */

        if (bg) {
            printf("[%d] (%d) %s", pid2jid(pid), pid, cmdline);
        } else {
            wait_fg_job(job_ins -> state);
        }
    }

    return;
}
示例#7
0
文件: eval.c 项目: Schwingg/shell
void eval(char *cmdline) {
    char *argv[MAXARGS]; // argv pour execve()
    char buf[MAXLINE]; // contient ligne commande modifiee
    int bg; // arriere-plan ou premier plan ?
    pid_t pid; // process id

    int indexJobLibre;

    strcpy(buf, cmdline);
    bg = parseline(buf, argv);
    if (argv[0] == NULL)
        return; // ignorer lignes vides

    if (!builtin_command(argv)) { // commande integree ?
        // si oui, executee directement
        if ((pid = Fork()) == 0) { // si non, executee par un fils
            setpgid(0, 0);

            if (execvp(argv[0], argv) < 0) {
                printf("%s: Command not found.\n", argv[0]);
                exit(0);
            }
        }

        indexJobLibre = getIndexLibre();
        tabJobs[indexJobLibre] = malloc(sizeof (job));
        tabJobs[indexJobLibre]->pid = pid;
        strcpy(tabJobs[indexJobLibre]->commande, argv[0]);


        if (!bg) { // le pere attend fin du travail de premier plan

            tabJobs[indexJobLibre]->etat = FG;
            printf("dans !bg: commande = %s\n", tabJobs[indexJobLibre]->commande);
            printf("getIndexFG() = %d --\n", getIndexFG());


        } else { // travail d'arriere-plan, on imprime le pid
            tabJobs[indexJobLibre]->etat = BG;
            printf("%d %s", pid, cmdline);


        }

    }

    while (getIndexFG() != -1) {
        printf("verif FG = %d\n", getIndexFG());
        afficheJobs();
        sleep(1);
    }


    return;
}
示例#8
0
文件: smsh1.c 项目: yangmiemie/books
int do_control_command(char** args)
{
  int rv;

  if (strcmp(args[0], "if") == 0)
  {
    if (if_state != NEUTRAL)
      err_ret("if error", "");

    last_result = process(args + 1);
    if_result = ((last_result == 0) ? SUCCESS : FAIL);
    if_state = WANT_THEN;
    rv = 0;
    printf("in do_control_command if, last_result = %d, if_result = %d, if_state = %d, arg + 1 = %s\n", last_result, if_result, if_state, *(args + 1));
  }
  else if (strcmp(args[0], "then") == 0)
  {
    if (if_state != WANT_THEN)
      err_ret("then error", "");

    if_state = THEN_BLOCK;
    rv = 0;
  }
  else if (strcmp(args[0], "else") == 0)
  {
    if (if_state != THEN_BLOCK)
      err_ret("else error", "");

    if_state = ELSE_BLOCK;
    rv = 0;
  }
  else if (strcmp(args[0], "fi") == 0)
  {
    if ((if_state != THEN_BLOCK) && (if_state != ELSE_BLOCK))
      err_ret("fi error", "");

    exec_cmd_ptr = exec_cmds;
    while(exec_number != 0)
    {
      if (!builtin_command(*exec_cmd_ptr))
        execute(*exec_cmd_ptr);

      freelist(*exec_cmd_ptr);

      ++exec_cmd_ptr;
      --exec_number;
    }

    if_state = NEUTRAL;
  }

  return rv;
}
示例#9
0
/**
 * @brief	: process user commands
 * @param	: args		array of strings
 * 		  exit_code	pointer to exit code passed to builtins
 * @return	  rv		result of command execution
 */
int process(char **args,int *exit_code, bool *syn_err)
{
	int	rv = 1;			/* defaults to 1 for failed exit */

	if ( args[0] == NULL )
		rv = 0;
	else if ( is_control_command(args[0]) )
		rv = do_control_command(args, syn_err);
	else if ( ok_to_execute(syn_err) )
		if ( !builtin_command(args,&rv,exit_code))
			rv = execute(args);
	return rv;
}
示例#10
0
文件: smsh1.c 项目: yangmiemie/books
int process(char** args)
{
  int rv;

  if (args[0] == NULL)
    return 0; 
  else if (is_control_command(args[0]))
    rv = do_control_command(args);
  else if ((rv = ok_to_execute(args)) == 1)
    if (!builtin_command(args))
      rv = execute(args);

  return rv;
}
示例#11
0
文件: eval.c 项目: EwanC/shell
//Evaluates the command line
void eval(char *cmdline){
 char *argv[MAXARGS]; //list of arguments
 char buf[MAXLINE]; //holds modified command line
 int bg;  //bg == 1 if job should be run in the background, otherwise foreground
 pid_t pid; //Process id

 strcpy(buf,cmdline);
 
 add_command_to_history(buf); //Records command in history

 bg = parseline(buf, argv);

 if(argv[0]== NULL)
   return;            //Ignore empty lines

 if(!builtin_command(argv)){
     execute_cmd(argv, bg);
 } 
 return;
}
示例#12
0
文件: shell.c 项目: 447327642/CSAPP2e
/* 
 * eval - evaluate a command line
 */
void eval(char *cmdline) 
{
    char *argv[MAXARGS]; /* argv for execve() */
    int bg;              /* should the job run in bg or fg? */
    pid_t pid;           /* process id */

    /* parse command line */
    bg = parseline(cmdline, argv); 
    if (argv[0] == NULL)  
	return;   /* ignore empty lines */
    if (!strcmp(argv[0], "quit"))
	exit(0);  /* terminate shell */

    if (!builtin_command(argv)) { 

	if ((pid = Fork()) == 0) {  /* child */

	    /* Background jobs should ignore SIGINT (ctrl-c)  */
	    /* and SIGTSTP (ctrl-z) */
	    if (bg) {
		Signal(SIGINT, SIG_IGN);
		Signal(SIGTSTP, SIG_IGN);
	    }

	    if (execve(argv[0], argv, environ) < 0) {
		printf("%s: Command not found.\n", argv[0]);
		fflush(stdout);
		exit(0);
	    }
	}

	/* parent waits for foreground job to terminate or stop */
	addjob(jobs, pid, (bg == 1 ? BG : FG), cmdline);
	if (!bg) 
	    waitfg(pid);
	else
	    printf("%d %s", pid, cmdline);
    }
    return;
}
示例#13
0
文件: shell.c 项目: mapan1984/Toys
/* Eval -- Evalute a command line */
void eval(char *cmdline){
    char *argv[MAXARGS];   // Argument list execve()
    char *environ;         // 环境变量列表environ暂设为空
    char buf[MAXARGS];     // Holds modified command line
    int bg;                // Should the job run in bg or fg?
    pid_t pid;

    strcpy(buf, cmdline);
    bg = parseline(buf, argv); // 解析以空格为delimiter的命令, buf ---> argv
                               // bg = 1 ;后台执行
                               // bg = 0 ; 前台执行(shell挂起)
    if(argv[0] == NULL){
        return; // Ignore empty lines
    }

    if(!builtin_command(argv)){ // 不是内置命令
        if((pid = fork()) == 0){ // Child runs user job
            if(execve(argv[0], argv, environ) < 0){
                printf("%s: Command not found.\n", argv[0]);
                exit(0);
            }
        }

        /* parent waits for foreground job to terminate */
        if(!bg){ // bg = 0 ; 前台执行(shell挂起)
            int status;
            if(waitpid(pid, &status, 0) < 0){
                unix_error("waitfg: waitpid error");
            }
        }else{   // 后台执行,即父进程无需挂起,用SIGCHLD处理程序回收子进程
            if(signal(SIGCHLD, handler) == SIG_ERR){ // 设置SIGCHLD处理程序
                unix_error("signal error");
            }
            printf("%d %s", pid, cmdline);
        }
    }
    return;
}
示例#14
0
void eval(char *cmdLine) {
	char *argv[MAXARGS], *argv2[MAXARGS], *pch;
	int bg, argc, fd[2];
	int status;
	pid_t pid, pid2;

	char _cmdLine[MAXLINE];
	char *cmd1;
	char *cmd2;

	strcpy(_cmdLine, cmdLine);

	if(strchr(_cmdLine, '|') != NULL) {
		cmd1 = strtok(_cmdLine, "|");
		cmd2 = strtok(NULL, "|");
	    strcat(cmd1, "\0");
		strcat(cmd2, "\0");
   		argc = 0;
		argv[argc] = strtok(cmd1, " \n");
		while(argv[argc] != NULL) {
			argc++;
			argv[argc] = strtok(NULL, " \n");
		}
   		argc = 0;
		argv2[argc] = strtok(cmd2, " \n");
		while(argv2[argc] != NULL) {
			argc++;
			argv2[argc] = strtok(NULL, " \n");
		}

		// fd[0] : read, fd[1] write
		if(pipe(fd) == -1) {
			printf("fail to call pipe()\n");
			exit(1);
		}
		if((pid = fork()) == 0) {
			close(1);
			dup(fd[1]);
			if(close(fd[0]) == -1 || close(fd[1]) == -1) {
				perror("close");
			}
			if(execvp(argv[0], argv) < 0) {
				printf("%s : Command not found.\n", argv[0]);
				exit(0);
			}
		}
		if((pid2 = fork()) == 0) {
			close(0);
			dup(fd[0]);
			if(close(fd[0]) == -1 || close(fd[1]) == -1) perror("close");
			if(execvp(argv2[0], argv2) < 0) {
				printf("%s : Command not found.\n", argv2[0]);
				exit(0);
			}
		}
		if(waitpid(pid, &status, 0) < 0) {
			fprintf(stderr, "waitfg : waidpid error");
		}
	} else {
		bg = parseLine(_cmdLine, argv);
		if(argv[0]==NULL) return;
		if(!builtin_command(argv)) {
			if((pid = fork()) == 0) {
				if(execvp(argv[0], argv) < 0) {
					printf("%s : Command not found.\n", argv[0]);
					exit(0);
				}
				if(bg) printf("[%d] %s\n", pid, cmdLine); fflush(stdout);
			}

			if(!bg) {
				if(waitpid(pid, &status, 0) < 0) {
					fprintf(stderr, "waitfg : waidpid error");
				}
			} else {
				printf("%d %s", pid, cmdLine);
			}
		}
	}
}
示例#15
0
文件: tsh.c 项目: MyMiracle/Shell-Lab
/*
 * eval - Evaluate the command line that the user has just typed in
 *
 * If the user has requested a built-in command (quit, jobs, bg or fg)
 * then execute it immediately. Otherwise, fork a child process and
 * run the job in the context of the child. If the job is running in
 * the foreground, wait for it to terminate and then return.  Note:
 * each child process must have a unique process group ID so that our
 * background children don't receive SIGINT (SIGTSTP) from the kernel
 * when we type ctrl-c (ctrl-z) at the keyboard.
 */
void
eval(char *cmdline)
{
    int bg;              /* should the job run in bg or fg? */
    struct cmdline_tokens tok;

    /* Parse command line */
    bg = parseline(cmdline, &tok);
    if (bg == -1) return;               /* parsing error */
    if (tok.argv[0] == NULL)  return;   /* ignore empty lines */

    /* Built-in Command */
    if (tok.builtins!=BUILTIN_NONE){
      builtin_command(&tok);
      return;
      }

    /* Common tasks for both foreground and background */

    pid_t pid;
    sigset_t mask;
    Sigemptyset(&mask);
    Sigaddset(&mask, SIGCHLD);
    Sigaddset(&mask, SIGINT);
    Sigaddset(&mask, SIGTSTP);
    /* Block signal receving in parent */
    Sigprocmask(SIG_BLOCK, &mask, NULL);

    if ((pid=Fork())==0){
      /* Unblock signal receiving in child */
      Sigprocmask(SIG_UNBLOCK, &mask, NULL);
      /* Changes the child's process group from the shell's */
      Setpgid(0,0);

      /* Change the input and output file descriptors */
      IOredirection(&tok);

      Execve(tok.argv[0], tok.argv, environ);
      /* Command not found */
      printf("Executable file not found\n");
      exit(0);
    }

    /* Foreground job*/
    if (!bg){
      if (!addjob(job_list, pid, FG, cmdline))
	return;
      Sigprocmask(SIG_UNBLOCK, &mask, NULL);
      wait_for_fg(pid);
      return;
    }

    /* Background job */
    if (bg){
      if (!addjob(job_list, pid, BG, cmdline))
	return;
      Sigprocmask(SIG_UNBLOCK, &mask, NULL);
      printf("[%d] (%d) %s\n", pid2jid(pid), pid, cmdline);
    }
    return;
}