Linux /模拟shell#include
#include
#include
#include
#include
#define MAXLINE 80
int
main(void)
{
charbuf[MAXLINE];
pid_tpid;
intstatus;
printf("%% ");
while (fgets(buf, MAXLINE, stdin) != NULL) {
if (buf[strlen(buf) - 1] == '/n'){
buf[strlen(buf) - 1] = 0;
}
if(strcmp(buf,"exit")==0)
exit(EXIT_SUCCESS);
if((pid= fork()) <0){
printf("Fork Error/n") ;
exit(EXIT_FAILURE);
}
else if (pid ==0){
//this is child process
//execlp("ls","ls","-al","/etc/passwd",(char*)0) ;
char filename[80] ;
int i ;
int commandBegin ;
//get file name
for(i = 0 ; i < 80 &&buf[i] !=' ' && buf[i] != 0; i++)
{
filename[i]=buf[i] ;
}
filename[i]='/0';
//get command argument,won't work fine with pipe command.
if(i
i++ ;
commandBegin=i;
for( ;buf[i] !=0;i++)
{
if(buf[i]==' ')
{
buf[i]='/0'; //replace ' ' by '/0'
}
}
if(commandBegin!=strlen(buf))
execlp(filename,filename,buf+commandBegin,(char*)0) ;
else
execlp(filename,filename,(char*)0);
exit(0);
}
waitpid(pid,&status,0);
pri swhile (fgets(buf, MAXLINE, stdin) != NULL) {
if (buf[strlen(buf) - 1] == '/n'){
buf[strlen(buf) - 1] = 0;
}
if(strcmp(buf,"exit")==0)
exit(EXIT_SUCCESS);
if((pid= fork()) <0){
printf("Fork Error/n") ;
exit(EXIT_FAILURE);
}
else if (pid ==0){
//this is child process
//execlp("ls","ls","-al","/etc/passwd",(char*)0) ;
char filename[80] ;
int i ;
int commandBegin ;
//get file name
for(i = 0 ; i < 80 &&buf[i] !=' ' && buf[i] != 0; i++)
{
filename[i]=buf[i] ;
}
filename[i]='/0';
//get command argument,won't work fine with pipe command.
if(i
i++ ;
commandBegin=i;
for( ;buf[i] !=0;i++)
{
if(buf[i]==' ')
{
buf[i]='/0'; //replace ' ' by '/0'
}
}
if(commandBegin!=strlen(buf))
execlp(filename,filename,buf+commandBegin,(char*)0) ;
else
execlp(filename,filename,(char*)0);
exit(0);
}
waitpid(pid,&status,0);
可能的输出结果:
rorger@ubuntu:~/bin/os$ ./myshell
% pwd
/home/rorger/bin/os
% whoami
rorger
% ps
PID TTY TIME CMD
4937 pts/2 00:00:00 bash
4971 pts/2 00:00:00 myshell
4977 pts/2 00:00:00 ps
% ls -a
. myshell2 myshell3.c myshell.c readme.txt
.. myshell2.c myshell4 myshell.o ?ο?????.png
myshell myshell3 myshell4.c OS_实验一.rar ʵ??һ.doc
% ls -l
总计 472
-rwxr-xr-x 1 rorger rorger 7490 2010-12-27 17:54 myshell
-rwxr-xr-x 1 rorger rorger 7492 2010-12-27 16:35 myshell2
-rw-r--r-- 1 rorger rorger 1294 2010-12-27 16:35 myshell2.c
-rwxr-xr-x 1 rorger rorger 7160 2010-12-27 17:06 myshell3
-rw-r--r-- 1 rorger rorger 97 2010-12-27 17:06 myshell3.c
-rwxr-xr-x 1 rorger rorger 7883 2010-12-27 17:13 myshell4
-rw-r--r-- 1 rorger rorger 2829 2010-12-27 17:13 myshell4.c
-rw-r--r-- 1 rorger rorger 1366 2010-12-27 17:54 myshell.c
-rw-r--r-- 1 rorger rorger 1312 2010-12-27 16:34 myshell.o
-rw-r--r-- 1 rorger rorger 197184 2010-12-27 16:07 OS_实验一.rar
-rw-r--r-- 1 rorger rorger 797 2009-12-25 21:42 readme.txt
-rw-r--r-- 1 rorger rorger 199302 2008-09-09 22:54 ?ο?????.png
-rw-r--r-- 1 rorger rorger 22016 2010-12-26 21:32 ʵ??һ.doc
注意:仅仅贴出了关键代码,相信其它部分自己补充,(*^__^*) 嘻嘻……