shell程序源代码清单: (2)源代码清单
源代码xsh.c: #include
#define BUFFERSIZE 256
//最简单的shell,只是简单的执行命令调用,没有任何的其他功能 int main()
{
char buf[BUFFERSIZE],*cmd,*argv[100]; char inchar;
int n,sv,buflength; buflength = 0; for(;;) {
printf(\
//处理过长的命令; inchar = getchar();
while (inchar != '\\n' && buflength < BUFFERSIZE ){ buf[buflength++] = inchar; inchar = getchar(); }
if (buflength > BUFFERSIZE){
printf(\ buflength = 0; continue; }
else
buf[buflength] = '\\0';
//解析命令行,分成一个个的标记 cmd=strtok(buf,\ if(cmd) {
if(strcmp(cmd,\ n=0;
argv[n++]=cmd;
while(argv[n++]=strtok(NULL,\ if(fork()==0) {
execvp(cmd,argv);
fprintf(stderr,\ exit(1);
} wait(&sv); buflength = 0; } } }
(3)测试结果:
[root@localhost Work]# make xsh.c make: Nothing to be done for `xsh.c'. [root@localhost Work]# make xsh make: `xsh' is up to date. [root@localhost Work]# ./xsh => ps
PID TTY TIME CMD 29297 pts/2 00:00:00 bash 29344 pts/2 00:00:00 xsh 29345 pts/2 00:00:00 ps => ps | more
ps: error: Garbage option. usage: ps -[Unix98 options] ps [BSD-style options]
ps --[GNU-style long options] ps --help for a command summary => ps > ps.txt
ps: error: Garbage option. usage: ps -[Unix98 options] ps [BSD-style options]
ps --[GNU-style long options] ps --help for a command summary => ls
fibno_timer.c ksamp.c psTimeInfo.c shell1.c shell2.c timer.c xshbk xsh.c xshrb.c
ksamp ls.txt shell1 shell1.c~ shell3.c xsh xshbk.c xshrb => chsh
Changing shell for root. New shell [/bin/bash]:
3、实验内容2
编写一个带有重定向和管道功能的Shell
(1)设计思路
通过fork()创建子进程,用execvp()更改子进程代码,用wait()等待子进程结束。
这三个系统调用可以很好地创建多进程。另一方面,编写的Shell要实现管道功能,需要用pipe(创建管道使子进程进行通信。 说明:
? 本程序允许同时有重定向和管道,也可以不带它们,但是管道数目不得超过一个
? 重定向的位置应该是在最后
? 设有一个内部命令exit用来退出Shell (2)源代码清单(参考)
#include
int hd;
char buf[256];
char *buf2,*buf3,*cmd,*cmd2,*cmd3,*argv[64],*argv2[64],*argv3[64]; int n,sv,fd[2]; for(;;) {
printf(\
if(fgets(buf,sizeof(buf),stdin)==NULL) exit(0); buf2=strstr(buf,\ buf3=strstr(buf, \ if (buf2)
*buf2++='\\0'; if(buf3)
*buf3++='\\0';
cmd=strtok(buf,\ if (cmd) {
if (strcmp(cmd,\ n=0;
argv[n++]=cmd;
while(argv[n++]=strtok(NULL,\ else exit(1); if (buf2){
cmd2=strtok(buf2,\ n=0;
argv2[n++]=cmd2;
while(argv2[n++]=strtok(NULL,\ if (buf3){
cmd3=strtok(buf3,\ n=0;
argv3[n++]=cmd3;
while(argv3[n++]=strtok(NULL,\
if (!cmd2){
if (fork() == 0) { execvp(cmd,argv);
fprintf(stderr,\ %s\\n\ exit(1);} wait(&sv); } else {
} } }
pipe(fd); if(fork()==0) { hd=-1;
dup2(fd[0],0);
if (cmd3) hd=open(cmd3, O_CREAT|O_WRONLY,0666); if (hd != -1 ) dup2(hd,1); close(fd[0]); close(fd[1]); close(hd);
execvp(cmd2,argv2);
fprintf(stderr,\ ******ERROR******: %s\\n\ } else if(fork()==0) { dup2(fd[1],1); close(fd[0]); close(fd[1]);
execvp(cmd,argv);
fprintf(stderr,\ ******ERROR******: %s\\n\ }
close(fd[0]); close(fd[1]); wait(&sv); wait(&sv);
相关推荐: