代码: 全选#include
#include
#include
#include
#include
#include
#include
//#define prompt "<<<
#define bufsize 50
char buffer[2048];
int version = 1;
char buf[bufsize];
char commandName[50];
char arg1[50];
char arg2[50];
//void parse(char *prompt,File *fp);
//void exec(char *commandName,char *arg1,char *arg2);
//void parse2(char *prompt,File *fp);
//void parr(char *prompt,File *fp);
void parse(FILE *fp);
void chaifen();
void exec(char *commandName,char *arg1,char *arg2);
void copy();
void copyOperation (int old,int new);
int main(){
while( 1)
{
int i;
//输出“$”提示符,等待用户输入命令行;
printf("<<<<<123 ");
parse(stdin);// 命令行; //命令行字符串分析:目标得出待运行程
//序的文件名 commandName,arg1,arg2
if (strcmp(buf,"logout\0")==0){
printf("logout2222");
break;}
else
chaifen();
//if(命令行==logout)
// exit( );
//if((i=fork( )) ==0 )
if ((i=fork())==0)
exec(commandName,arg1,arg2);
else
sleep(5);
}
return 0;
}
//void parse(char *prompt,File *fp)
void parse(FILE *fp)//char *prompt,
{
int i,j;
fgets(buf, bufsize, stdin);
printf("buf= %s",buf);
//fputs(buf,stdout);//fputs(fgets(s,80,stdin),stdout); 检验是不是把buf的内容输出
}
void chaifen()
{
int i,j;
//fflush(stdin);
for (i=0;(buf[i]!=' ')&&(buf[i]!='\n');i++)
{
// printf("11111111\n");
commandName[i]=buf[i];
// flag=1;
}
// printf("2222\n");
commandName[i]='\0';
// printf(" CommandName=%s\n",commandName);
j=0;
for (i=i+1;(buf[i]!=' ')&&(buf[i]!='\n');i++)
{
arg1[j]=buf[i];
j++;
}
arg1[j]='\0';
// printf(" arg1=%s\n",arg1);
j=0;
for (i=i+1;(buf[i]!=' ')&&(buf[i]!='\n');i++)
{
arg2[j]=buf[i];
j++;
}
arg2[j]='\0';
//printf(" arg2=%s\n",arg2);
}
void exec(char * commandName,char *arg1,char *arg2 )
{
if ( (strcmp(commandName,"copy")==0) &&(strcmp(arg1,"file1")==0)&&(strcmp(arg2,"file2")==0) )
copy();
else
printf("PID=%d!\n ",getpid());
}
void copy()
{
int i = 0;
int fdold,fdnew;
fdold = open("file1", O_RDONLY);
if(fdold == -1)
{
printf("can not open file %s\n","file1");
exit(1);
}
fdnew = creat("file2", 0666);
copyOperation (fdold, fdnew);
printf ("This is process %d\n", getpid() );
printf("Copy Done!From %s To %s\n", "file1","file2");
exit(0);
}
void copyOperation (int old,int new)
{
int count;
while ((count=read(old,buffer,sizeof(buffer)))>0)
write(new, buffer, count);
return;
}