【发布时间】:2017-07-06 02:00:07
【问题描述】:
我正在尝试创建一个简单的 c 程序,该程序接受用户输入,将其传递给底层 shell 并返回用户命令的输出。例如:pwd 将给出当前工作目录。
我想在无限循环中使用 fork() 和 exec() 执行此操作,但我面临两个问题:
- 我的循环在第一次运行后终止
-
它只需要第一个参数。 'ls -ltr' 会给我输出 'ls' 而不是 'ls -ltr'
int runit(char*); void main() { int pid=0; char command[50]; while(1) { int d=0; printf("Please enter your command!\n"); scanf("%s", &command); switch (pid = fork()) { case 0: // a fork returns 0 to the child printf("Child process \n"); d=runit(command); if(d==-1){ printf("command not found \n");} break; default: wait(5); // a fork returns a pid to the parent printf("Parent process \n"); break; case -1: //if something went wrong perror("fork"); exit(1); } } } int runit(char* command) { //executing the command char path[50]="/bin/"; int d = execl(strcat(path,command),command,NULL,NULL); return(d); }
谁能告诉我我做错了什么或指导我如何纠正这个问题。
【问题讨论】:
标签: c shell operating-system