【发布时间】:2015-06-24 10:44:20
【问题描述】:
我正在使用 linux,我想在 c 中编写一个程序,该程序从用户读取命令,直到我输入 stop。对于每个命令,主程序将创建一个进程 A,该进程将创建另一个进程 B。进程 B 将执行用户输入的命令。我想使用 exec 使其工作,但它仅适用于一个单词命令(例如:pwd,ls),如果我输入例如ls -l,它表示没有这样的文件或目录。到目前为止我写的代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define N 100
int main() {
char input[N];
scanf(" %[^\n]s",input); //reads from user inputs that can include space
while (strcmp(input,"stop") != 0) { // verifies if entered command == stop
int a;
a = fork();//creates the process A
if (a == -1) {
perror("fork imposibil!");
exit(1);
}
if (a == 0) {
printf("a\n");//i printed that to verify if my fork works
int b;
b = fork();//creates process B
if (b == -1) {
perror("fork imposibil!");
exit(1);
}
if (b == 0) { // the part that makes me problems , i try to use exec to execute the command that is stored in input
printf("b\n");
if (execlp(input,"",(char*) 0) < 0) {
perror("Error exec");
exit(0);
}
exit(0);
}
wait(0);
exit(0);
}
wait(0);
scanf(" %[^\n]s",input);
}
return 0;
}
有人可以帮帮我吗? 附言我不认为我的代码难以阅读,但我希望现在更好
【问题讨论】:
-
首先学习如何编写可读的代码,然后你可能会问一个问题,因为阅读你的代码几乎是不可能的。例如,我在
perror()之后没有看到exit(),根本没有看到,我想,哎呀,他报告了错误,但仍然忽略它们。而且我认为您应该从子进程中调用_exit(0)而不是exit(0)。