日期:2014-05-16  浏览次数:20783 次

自己编写的的shell不能执行外部命令
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<stdio.h>
#include<string.h>
#include <signal.h>
#define MAXLINE 128
#define MAXARGC 128
typedef struct PC
{
char pc_name[20];
pid_t t;
//int state;
struct PC *next;
}Process;
Process *head;
extern char **environ; 
char p[][20] = {"cd","environ","echo","help","jobs"};
void cmdLine_Analyse(char *cmdLine,char **argv,char cmd[]);
int cmdRun(char **argv,char cmd[]);
int cd_fun(char **argv);
void environ_fun();
void echo_fun(char **argv);
int help_fun();
int jobs_fun(char **argv);
int Is_Outcmd(char **argv);
void CreateProcessNode();
void InsertProcessNode(char *cmd,pid_t t);
void DeleteProcessNode(pid_t pid);
static void wait_child(int sig_type);
void set_singnal();
int new;
///////////////////////////////////////////main//////////////////////////////
int main()
{
//process Pcb;
char *argv[MAXARGC];
char dir[MAXARGC];
char cmdLine[MAXLINE];
char cmd[MAXARGC];
int n = 0,i;
CreateProcessNode();
while(1) 
{
printf("[%s]$PS1",get_current_dir_name());
gets(cmdLine);
//strcpy(cmdLine,"date");
if(cmdLine[strlen(cmdLine) - 2] == '&')
new = 1;
if(!strcmp(cmdLine,"quit") || !strcmp(cmdLine,"exit") || !strcmp(cmdLine,"bye"))
break;
cmdLine_Analyse(cmdLine,argv,cmd);
cmdRun(argv,cmd);
}
return 0;
}
///////////////////////////////////////////////signal///////////////////////////////////////////////////////////
static void wait_child(int sig_type)
{
int status;
pid_t pid = wait(&status);
  DeleteProcessNode(pid);
}

void set_signal()
{

if (signal(SIGCHLD, wait_child) == SIG_ERR) {
perror("Signal");
exit(EXIT_FAILURE);
}
}
/////////////////////////////cmdLine_devide////////////////////////////////////////
void cmdLine_Analyse(char *cmdLine, char **argv,char cmd[] )
{
char *temp;
temp = strtok(cmdLine , " ");
int argc = 0;
while(temp != NULL)
{
if(argc == 0)
{
strcpy(cmd,temp);
}
argv[argc++] = temp; 
temp = strtok(NULL," ");
}  
if(!strcmp(argv[argc-1],"&"))
{
argv[argc - 1] = '\0';
new = 1;
}
else
argv[argc] = NULL;
}
///////////////////////////////cmdRun/////////////////////////////////////////
int cmdRun(char **argv,char cmd[])
{
int i;
for(i = 0;i < 5;i++)
{
if(!strcmp(p[i],cmd))
  break;
}
switch(i)
{
case 0:
cd_fun(argv);
break;
case 1:
environ_fun();
break;
case 2:
echo_fun(argv);
break;
case 3:
help_fun();
break;
case 4:
Jobs_fun();
break;

}
if(i == 5)
{
 if(!Is_Outcmd(argv))
{
printf("ERROR");
}
//Is OutCmd
}
}
////////////////////////////echo_fun////////////////////////////////////////
void echo_fun(char **argv)
{
char **var;
for(var = argv + 1; *var != NULL;var++)
{
printf("%s ",*var);
}
printf("\n");
}
//////////////////////////////////////cd_fun////////////////////////////////
int cd_fun(char **argv)
{
if(chdir(argv[1]))
{
printf("改变目录失败\n");
}
return 0;
}
void environ_fun()
{
char **var;
for(var = environ; *var != NULL; var++)
{
printf("%s\n",*var);
}
}
int help_fun(