- 论坛徽章:
- 0
|
//程序有错,大侠们帮改改,不胜感激
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/stat.h>
#define MAX 1024
/*字符串分析函数
参数1 buf --源字符串
参数2 args--解析后的字符串数组首址
返回值--解析后的字符串个数
*/
int parse (char *buf, char **args)
{
int num=0;
while (*buf != '\0')
{
while((* buf ==' ')||(* buf == '\t'||(*buf == '\n')))
*buf++ = '\0'; //该循环是定位到命令中每个字符串的第一个非空的字符
*args++ = buf; //将找到的非空字符串 依次赋值给args[i]。
++num;
while ((*buf!='\0')&&(* buf!=' ')&&(* buf!= '\t') && (*buf!= '\n'))//正常的字母就往后移动,直至定位到非空字符后面的第一个空格。
buf ++;
}
*args = '\0';
return num;
}
main(int argc ,char *argv[])
{
/*循环进行以下过程:
(1)输出命令提示符如两个%
(2)使用fgets获取用户输入
(3)解析字符串
(4)判断用户的输入是否代表结束
是则退出
否则创建子进程
子进程调用execvp执行用户输入的命令
父进程等待子进程退出后输出命令提示符
进行下一次循环过程
*/
char src[MAX];
char *dest[100];
int count;
do{
puts("请输入Linux系统命令");
printf(">");
fgets(src,MAX,stdin);
if(src[0]=='*')
break;
else{
count=parse(src,dest);
if(fork())
execvp(src,dest);
else{
printf("end\n");
wait(NULL);
}
}
wait(NULL);
}while(1);
} |
|