【发布时间】:2019-02-25 10:01:57
【问题描述】:
我正在用 C 语言创建一个简单的 Linux 命令 shell。我无法理解我的代码出现问题的地方。 “commands”是我希望作为一个父进程的子进程同时执行的 Linux 命令字符串列表。全部执行完毕后,我希望父级退出该函数。但是,当我调用 exit(0) 时,for 循环继续并再次解析当前命令,导致 args 在 execvp 中再次执行。我在这里正确使用 fork() 和 wait() 吗?我也尝试过使用 waitpid(),但没有成功。
void executeShell(char** commands){
char **arr = commands;
char *c;
pid_t pid, wpid;
int status = 0;
for (c = *arr; c; c=*++arr){
// printf("%d-\n", strcmp(command, "exit"));
if (strcmp(c, "exit") == 0){
EXIT = 1;
return;
}
printf("Running command \'%s\'...\n", c);
char** args = parseStringToTokenArray(c, " ");
free(args);
/* fork and execute the command */
pid = fork();
if(pid < 0){
perror("fork() error\n");
return;
}
/* child process executes command */
else if (pid == 0){
/* 'cd' is not a part of /bin library so handle it manually */
if (strcmp(args[0], "cd") == 0){
changeDirectory(args[1]);
}
else if (strcmp(args[0], "sdir") == 0){
searchDirectory(args[1]);
}else{
/* parse commands with arguments */
execvp(args[0], args);//execute the command
}
exit(0);// <-----command is finished, so why no exit?
}
}
/* wait for children to complete */
while((wpid = wait(&status)) > 0);
}
【问题讨论】:
-
父亲执行的代码块在哪里?
-
正如@nissimabehcera 提到的,看起来父亲的执行仍在循环中。
-
为什么你在创建它之后就
free(args);?难道你不应该等到你使用它(或不再需要它)之后吗? -
你小时候要分叉什么命令?它们是完成还是无限期运行?