首页 > 解决方案 > 同时执行fork进程

问题描述

我正在用 C 制作基本的 shell。

每行可能包含多个用;字符分隔的命令。由 a 分隔的每个命令;都应该同时或同时运行。(我知道这与标准 Linux shell 的行为不同。)在那之后,shell 不应该打印下一个提示或接受更多输入,直到所有这些命令都完成执行。例如,以下行都是有效的,并且指定了合理的命令:

prompt>
prompt> ls
prompt> /bin/ls
prompt> ls -l
prompt> ls -l ; cat file
prompt> ls -l ; cat file ; grep foo file2

例如,在最后一行,命令ls -lcat file应该grep foo file2同时运行。

我可以用我的 splitLine 函数分割线。

```// Function to split a line into constituent commands
char **splitLine(char *line)
{
    char **tokens = (char **)malloc(sizeof(char *) * 64);
    char *token;
    int pos = 0, bufsize = 64;
    if (!tokens)
    {
        printf("\nBuffer Allocation Error.");
        exit(EXIT_FAILURE);
    }
    token = strtok(line, " ");
    while (token != NULL)
    {
        printf("%s", token);
        if (!strcmp(token, ";"))
        {
            tokens[pos] = NULL;
        }else
        {
            tokens[pos] = malloc(sizeof(char) * (strlen(token) + 1));
            strcpy(tokens[pos], token);
        }
        
        pos ++;
        if (pos >= bufsize)
        {
            bufsize += 64;
            line = realloc(line, bufsize * sizeof(char *));
            if (!line)
            {
                printf("\nBuffer Allocation Error.");
                exit(EXIT_FAILURE);
            }
        }
        token = strtok(NULL, " ");
    }
    return tokens;
}```

但我不知道如何同时执行所有命令。这是我的执行功能。

// Function to create child process and run command
int myShellLaunch(char **args)
{

    pid_t pid, wpid;
    int status;
    pid = fork();
    if (pid == 0)
    {
        // The Child Process
        if (execvp(args[0], args) == -1)
        {
            perror("myShell: ");
        }
        exit(EXIT_FAILURE);
    }
    else if (pid < 0)
    {
        //Forking Error
        perror("myShell: ");
    }
    else
    {
        // The Parent Process
        do 
        {
            wpid = waitpid(pid, &status, WUNTRACED);
        } while (!WIFEXITED(status) && !WIFSIGNALED(status));
    }
    return 1;
}

标签: clinuxshellprocess

解决方案


推荐阅读