我的代码
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
char * arg_list[3];
arg_list[0] = "ls";
arg_list[1] = "-l";
arg_list[2] = 0;
char *arg_list2[3];
arg_list2[0] = " ps";
arg_list2[1] = "-ef";
arg_list2[2] = 0;
for(int i=0;i<5;i++){ // loop will run n times (n=5)
if(fork() == 0) {
if (i == 0){
execvp("ls", arg_list);
}else if(i==1){
execvp("ps" , arg_list2);
}else if(i>1){
printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid());
exit(0);
}
}
}
for(int i=0;i<5;i++) // loop will run n times (n=5)
wait(NULL);
}
我正在尝试修改它
#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
for(int i=0;i<5;i++){ // loop will run n times (n=5)
if(fork() == 0) {
printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid());
execlp(argv[i],argv[i],argv[i+1],(char*)NULL);
exit(0);
}
}
for(int i=0;i<5;i++) // loop will run n times (n=5)
wait(NULL);
}
-- 需要指导和理解
我正在尝试制作自己的小 shell 程序。当我运行第一个代码时工作正常,在命令行上运行所有命令。但我无法知道和定义用户可能输入的所有命令。所以我试图获取一个基本代码,它可以运行用户输入的单个或多个命令。我尝试使用 execlp ,但它无法编译,说 argv 未定义,这是真的,因为我不想专门定义它。
最佳答案
I am trying to make my own tiny little shell program. When I run my first code works fine, runs all commands on the command line. But I cannot know and define all commands the user might enter.
当然...... shell 程序的目的基本上是:
- 读取用户输入
- 执行用户输入
- 返回执行结果。
您的代码中没有任何内容可以读取用户输入......
So i am trying to get a base code which could run any commands single or multiple entered by user.
所以读取用户输入;-)
I tried using execlp where it does not compile saying argv is not defined which is true as i don't want to specifically define it.
当然...但是 GCC 如何猜测 `argv[]̀ 必须自动填充用户输入? 用 C 语言编码时没有什么是自动的。您必须手动管理它。
另外,请注意 argc
, argv
等envp
通常保留给 main()
功能:
main(int argc, char **argv, char **envp)
所以你可以使用其他东西来构建你的命令数组。
在伪代码中,您必须实现的是:
quit=0
while (quit = 0) {
command_to_run = read_user_input();
if (command_to_run == "exit") {
quit = 1;
} else {
execute(command_to_run);
}
}
一些建议:
尝试使用更多功能。例如,实现
fork_and_run(char **cmd)
函数来 fork 然后执行用户提供的命令。 Il 将使您的代码更具可读性且易于维护。仔细阅读手册页:您应该知道的所有内容(例如,提供给
execvp()
的数组必须以 NULL 结尾)都写在其中。您的调试消息应打印到
stderr
。命令运行的结果必须打印到stdin
,所以使用fprintf()
而不是printf()
写入正确的流。我会使用
#define debug(x) fprintf(stderr, x)
或类似的调试输出,以便您稍后可以轻松禁用;-)
关于shell - 我正在尝试编写一个 shell 程序来一次执行多个命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58908912/