#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void FenliCanshu(int *argc,char argv[100][256], char *arg[100]);//分离参数
void Exec_cmd(char *arg[100]);//执行命令
void FenliCanshu(int *argc,char argv[100][256], char *arg[100])
{
char commod[256], ch;
int i;
int j,k;
j = 0;
k = 0;
memset(commod, '\0', 256);
while(1)
{
printf("myshell$$ ");
while((ch = getchar()) != '\n'){
commod[strlen(commod)] = ch;
}
if(commod[0] == '\0')
continue;
if(commod[0] == ' ' ){
printf("The commmod is Error!\n");
memset(commod, '\0', 256);
continue;
}
if(commod[strlen(commod) - 1] == ' '){
commod[strlen(commod) - 1] = '\0';
}
for(i = 0; commod[i] != '\0'; i++){
argv[j][k++] = commod[i];
if(commod[i] == ' '){
argv[j][strlen(argv[j]) - 1] = '\0';
j++;
k = 0;
}
}
*argc = j + 1;
for(j = 0; j < *argc; j++)
{
arg[j] = (char *)argv[j];
}
arg[*argc] = NULL;
if(strcmp(commod, "exit") == 0)
exit(0);
if(strlen(commod) > 256){
printf("The commod is Error!\n");
memset(commod, '\0', 256);
continue;
}
Exec_cmd(arg);
memset(commod, '\0', 256);
j = 0;
k = 0;
for(i = 0; i < 100; i++)
memset(argv[i], '\0', 256);
for(i = 0; i < 100; i++)
arg[j] = (char *)argv[j];
}
}
void Exec_cmd(char *arg[100])
{
pid_t pid;
pid = fork();
if(pid == 0){
if(execvp(arg[0], arg) == -1)
{
printf("Failed!\n");
exit(0);
}
}
else if(pid > 0){
wait(NULL);
}
}
int main()
{
int argc;
char *arg[100];
char argv[100][256];
FenliCanshu(&argc, argv, arg);
return 0;
}
|