2016-09-20 40 views
0

我正在做一个自制的外壳(非常简单的外壳)。我决定采用使用execvp的路由,因为我的路径不是我的shell的可变元素。我遇到了一个关于如何一次分叉和执行多个进程的逻辑问题。叉和执行多个进程同时

我的程序应该用命令工作这样:

ls ; echo hello ; cat shell.c 

其中每个 “;”表示我们希望同时运行这些进程。所以在我们的终端输出中,我们应该混合使用这些命令。

要阐述我想解释一下我的程序是如何工作的:

A. Intake full command line into char array with a grab line function 
B. Split the char array received from the last function by delimiters and place into an array of char arrays (pointer to pointer). 
C. If one of the elements in our array of char arrays is ";" we can assume that multi commands are necessary. This is where I have trouble. 

我已经尽可能知道我到底需要多少进程叉和这样得到的,但我似乎无法换我请回顾一下如何将所有这些函数及其参数一次传递给execvp函数。我应该使用临时数组吗?我知道这不应该是复杂的,但由于某种原因,我无法弄清楚。我提交下面我的发射功能,该引入口炭数组的数组并执行相应基于被当需要多命令(通过我的分割线功能)设置我“multiCommand”可变

int launch(char **args){ 

    pid_t pid; 
    int status; 
    int i = 0; 

    if(strcmp(args[0], "quit") == 0){ 
     exit(EXIT_SUCCESS); 
    } 

    if(strcmp(args[0], ";") != 0){ 
     printf("Essential Command Found : %s\n", args[0]); 
     numFork++; 
    } 


    if(multiCommand == 1){ 
     //Handle Multicommands here 
     printf("Multi Commands Handling Here\n"); 

     for(; i < elements - 1; i++){ 
      if(strcmp(args[i], ";") == 0){ 
       if((i + 1) < elements){ 
        printf("Essential Command Found : %s\n", args[i + 1]); 
        numFork++; 
       } 
      } 
     } 

     //This is where I need to figure out what to do 

     printf("Fork: %d times\n", numFork); 


    }else if (multiCommand == 0){ 
     pid = fork(); 
     if(pid == 0){ 
      execvp(args[0], args); 

     }else{ 
      wait(&status); 
     } 
    } 

    multiCommand = 0; 
    elements = 0; 

    return 1; 
} 
+3

旁注:在标准弹','一般意味着只有在另一端结束后运行一个,'&'意味着在后台运行,导致下一个结束无需等待前一个结束就运行。 – kaylum

+2

您需要为每个要运行的进程分叉一次。相应的孩子会知道它要执行哪个命令(你必须确保它)。 'execvp()'系统调用将只运行一个命令,而不是很多(但一个命令可能是一个shell,然后运行许多命令)。 –

回答

2

一般想法是对不同的命令进行for循环,并为它们分别赋值。

E.g.

for(int i = 0; i < commandCount; i++) { 
    int pid = fork(); 
    if(pid == 0) { //this is the child (don't forget to check for errors and what-not) 
     execCommand(all, of, the, info, needed); 
    } 
} 

您可以使用strtok()轻松获取不同的命令。
下面是一个例子:

#include <string.h> 
#include <stdio.h> 
int main() { 
    char input[] = "abc;def;ghi"; 
    char *token = strtok(input, ";"); 
    while(token != NULL) { 
     printf("%s\n", token); 
     token = strtok(NULL, ";"); 
    } 
    return 0; 
} 

输出:

abc 
def 
ghi 

最终的功能将是这个样子:

char *token = strtok(input, ";"); 
while(token != NULL) { 
    int pid = fork(); 
    if(pid == 0) { 
     //token is one command 
     //parse the different parts here 
     execCommand(args, to, exec); 
    } 
    token = strtok(NULL, ";"); 
} 
+0

谢谢,我想最难的部分是将命令作为“execvp”的第二个参数传递给下一个分号。我似乎无法弄清楚那一部分。 –

+1

如果你有它的单一命令的工作,你可以将输入分解成一个char数组数组,并通过你为单个命令做的相同的方式。 – Riley

+1

@ s.gang我希望这个编辑有帮助 – Riley