c - 同时 fork 和 exec 多个进程

标签 c linux shell fork exec

我正在研究一个自制的 shell(非常简单的 shell)。我决定采用使用 execvp 的方式,因为我的路径对于我的 shell 来说不是一个可变元素。我遇到了一个问题,提出了如何同时 fork 和执行多个进程的逻辑。

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

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.

我已经确切地知道我需要 fork 多少个进程等等,但我似乎无法理解如何将所有这些函数及其参数同时传递给 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;
}

最佳答案

一般的想法是对不同的命令进行 for 循环并 fork 它们中的每一个。

例如

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, ";");
}

关于c - 同时 fork 和 exec 多个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39603612/

相关文章:

c++ - 找不到 libtoolize 和 glibtoolize

linux - 将输出存储到 shell 变量中

c - 类似 Printf 的函数,具有可选格式字符串参数和 GCC 格式类型检查

linux - 查找固定字符串并在 linux 中替换

c - 在 Mac 上调试段错误?

c - linux fcntl 文件锁定超时

linux - Bash 中的脚本参数

linux - 在标题后打印文件中的第二个字段。

c - 释放链表中的前一个节点

在 Linux 中获取 IP 地址的接口(interface)名称的 C 代码