c - 同时执行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 -l
和cat 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;
}
解决方案
推荐阅读
- ios - 我来自 firebase 数据库的数据没有加载到我的 tableview 中
- azure - VM 上未安装 Azure Log Analytics 代理
- flutter - 扩展小部件中的平面按钮未正确舍入
- kendo-ui - Kendo Grid 分页:当前页面在中间
- python - 将 dpi 添加到 seaborn 或使用给定的 dpi 导出它们
- sql - 如何维护 T-SQL 中动态填充列的字段大小
- php - Laravel 调试栏在我在 chrome 中取消后没有显示,但在 firefox 上工作
- sql - SQL - 使用 string_agg 两次
- ssl - Nginx Stream SSL 连接到 Synology 时出现错误 500
- lua - io.read() 是读取字符吗?