s.g*_*ang 1 c linux shell fork exec
我正在自制外壳(非常简单的外壳)上工作。我决定采取使用execvp的方法,因为我的路径对于我的shell来说不是可变元素。我遇到了一个关于如何一次分叉和执行多个进程的逻辑问题。
我的程序应使用如下命令:
ls ; echo hello ; cat shell.c
Run Code Online (Sandbox Code Playgroud)
其中每个“;” 表示我们希望同时运行这些过程。因此,在我们的终端输出中,我们应该同时使用这些命令。
详细地说,我想解释一下我的程序如何工作:
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.
Run Code Online (Sandbox Code Playgroud)
我到目前为止已经确切地知道需要分叉多少个进程,但是我似乎无法将所有这些函数及其参数立即传递给execvp函数。我应该使用临时数组吗?我知道这不应该那么复杂,但是由于某种原因我无法弄清楚。我在下面提交我的启动函数,该启动函数接收一个char数组并根据我的“ 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;
}
Run Code Online (Sandbox Code Playgroud)
一般的想法是在不同的命令之间有一个for循环,并分叉每个命令。
例如
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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用轻松获得不同的命令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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
abc
def
ghi
Run Code Online (Sandbox Code Playgroud)
最终功能将如下所示:
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, ";");
}
Run Code Online (Sandbox Code Playgroud)