2007年5月26日土曜日

inux Programming: 编写一个简单的Shell命令解释程序

这个版本的Shell支持管道功能和I/O重定向.
下一个版本将增加对内建(buildins)命令的支持,如if ..then else等控制语句的支持.
-------------CODE-------------------

#include
#include
#include
#include
#include
#define OPEN_MAX 10
#define MAXNAME 100
#define FALSE 0
#define TRUE 1
char *readcmd( FILE *fp ); //读入命令行字符串
char **getarg(char *argv); //把命令行字符串分解成字符数组指针
void getfile(char *name); //获得重定向文件名
void freearg(char **arg); //释放内存
char *buf; //存放用户输入的字符串
char *p; //指向buf的指针
int cmdnum; //记录命令个数
int pipefd[2]; //保存管道文件描述符
int wait_pid; //记录父进程PID
char infile[MAXNAME+1]; //输入重定向文件
char outfile[MAXNAME+1]; //输出重定向文件
int background; //记录命令是否在后台执行
int append; //记录是否写入文件末尾
struct cmd{
char ** argv; //命令行参数
int infd; //输入文件描述符
int outfd; // 输出文件描述符
}cmdline[BUFSIZ]; //命令行结构数组
int main()
{
pid_t pid;
int status;
int i, fd;
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_IGN); //处理中断(Ctrl-C)和退出(Ctrl-\)信号
printf("%% ");


while( (buf = readcmd(stdin)) != NULL ){
//-----------初始化-----------------
int k;
cmdnum = 0;
background = FALSE;
infile[0] = '\0';
outfile[0] = '\0';
append = FALSE;
for( k = 0; k < OPEN_MAX; k++ )
{
cmdline[k].infd = 0;
cmdline[k].outfd = 1;
}
for( k = 3; k < OPEN_MAX; k++ )
close(k);
fflush(stdout); //清空输出缓冲区
p = buf;
//-----------计算命令个数并获得命令参数----------
for(i = 0; i <= cmdnum; i++)
cmdline[i].argv = getarg(buf);

if( infile[0] != '\0' )
cmdline[0].infd = open(infile, O_RDONLY);
if( outfile[0] != '\0' )
if( append == FALSE )
cmdline[cmdnum].outfd = open(outfile, O_WRONLY | O_CREAT | O_TRUNC, 0666);
else
cmdline[cmdnum].outfd = open(outfile, O_WRONLY | O_CREAT | O_APPEND, 0666);
if( background == TRUE )
signal(SIGCHLD, SIG_IGN);
else
signal(SIGCHLD, SIG_DFL);
//-----------执行命令行-------------
for(i = 0; i <= cmdnum; i++)
{
//-----------处理管道-------------
if( i < cmdnum )
{
pipe(pipefd);
cmdline[i+1].infd = pipefd[0];
cmdline[i].outfd = pipefd[1];
}



if ( pid = fork() )
wait_pid = pid;
else if ( pid == 0 ){
if( cmdline[i].infd == 0 && background == TRUE )
cmdline[i].infd = open("/dev/null", O_RDONLY);
if(cmdline[i].infd != 0)
{
close(0);
dup(cmdline[i].infd);

}
if(cmdline[i].outfd != 1)
{
close(1);
dup(cmdline[i].outfd);

}

if( background == FALSE )
{
signal(SIGINT, SIG_DFL);
signal(SIGQUIT, SIG_DFL);
}
for( k = 3; k < OPEN_MAX; ++k)
close(k);
execvp(cmdline[i].argv[0], cmdline[i].argv);

}
if(fd = cmdline[i].infd)
close(fd);
if((fd = cmdline[i].outfd) != 1)
close(fd);
}
if( background == FALSE )
while ( waitpid(pid, &status, 0) != wait_pid )
;

printf("%% ");
//-------释放内存-----------
for(i = 0; i <= cmdnum; i++)
freearg(cmdline[i].argv);
free(buf);
}

exit(0);
}
void freearg(char **arg)
{
char **cp = arg;
while(*cp)
free(*cp++);
free(arg);
}
char *readcmd(FILE *fp)
{
char *buf;
int buflen = 0;
int i = 0;
int c;

while( (c = getc(fp)) != EOF ){
if( i +1 >= buflen ){
if( buflen == 0 ){
buf = (char*) malloc( BUFSIZ );
if( buf == NULL )
return NULL;
}
else{
buf = (char *)realloc(buf, buflen + BUFSIZ);
if( buf == NULL )
return NULL;
}
buflen += BUFSIZ;
}
if ( c == '\n' )
break;
buf[i++] = c;
}
if( c == EOF && i == 0 )
return NULL;
buf[i] = '\0';
return buf;
}
char **getarg(char * argv)
{
char **args;
if( (args = (void *)malloc(BUFSIZ)) == NULL )
{
printf("out of memory\n");
return NULL;
}

int bufsize = sizeof(argv)/sizeof(argv[0]);
char argbuf[bufsize];
char *cp = argbuf;
char *end;
char *start = argbuf;
char * tempstr;
int len;
int i = 0;
while( *p != '\0' )

{
while( *p == ' ' || *p == '\t' )
p++; //去掉多余的空格
if( *p == '\0' )
break;
if( *p == '|') //管道,使命令数加1
{
if( *(p+1) == ' ' )
p +=2; //跳过空格
else
p++;
cmdnum++;
break;
}
if( *p == '<' ) //输入重定向
{
if( *(p+1) == ' ' )
p +=2;
else
p++;
getfile(infile);
break;
}
if( *p == '>' ) //输出重定向
{
if( *(p+1) == ' ' )
p +=2;
else
p++;
if( *p == '>' ) //追加到文件末尾
{
if( *(p+1) == ' ' )
p +=2;
else
p++;
append = TRUE;
}
getfile(outfile);
break;
}
if( *p == '&' ) //后台执行命令
{
if( *(p+1) == ' ' )
p +=2;
else
p++;
background = TRUE;
break;
}
*cp++ = *p++;
if( *p == ' ' || *p == '\0' )
{
*cp = '\0';
end = cp;
len = end - start;
if( (tempstr = (char *)malloc(len + 1)) == NULL )
{
printf("out of memory\n");
return NULL;
}
strncpy(tempstr, start, len);
tempstr[len] = '\0';
if( i + 1 > BUFSIZ )
{
if( (args = (void *)realloc(args, BUFSIZ * 2)) == NULL )
{
printf("out of memory\n");
return NULL;
}
}
args[i++] = tempstr;
start = end;
if( *p == '\0')
break;
p++;
}
}
args[i] = NULL;

return args;
}
void getfile(char *name)
{
int i;
for( i = 0; i < MAXNAME; ++i )
{
if( *p == ' ' || *p == '|' || *p == '>' || *p == '\0' ||
*p == '<' || *p == '&' || *p == '\t' )
{
*name = '\0';
return;
}
else
*name++ = *p++;

}
*name = '\0';
}

43 件のコメント:

匿名 さんのコメント...

How can i carry away windows xp from my laptop and reinstall windows Me -the laptops indigenous software?
I procure recently bought a acquainted with laptop that is old. The himself I had bought it from had installed windows xp on it, regular for all that it at came with windows Me. I after to eradicate the windows xp because it runs slows on the laptop because it takes up more tribute than the windows Me would. Also I want to unseat windows xp because it is an forbidden copy. So when I tried to run updates on it, windows would not install updates because the windows xp is not genuine. [URL=http://phckoke.hostific.com]air lift 72000 wireless[/URL]
----------------------------------------------------------------------

Answers :

It's better to relinquish [URL=http://igeifea.hostific.com/alexandra-paressant.html]alexandra paressant[/URL] Windows XP and good upgrade your laptop. It's much better. [URL=http://rxoeayp.hostific.com/perimenopause-etiology.html]perimenopause etiology[/URL] In addition to, Windows XP is trail [URL=http://bwacrdl.instantfreehosting.com/arabian-breeding-auction.html]arabian breeding auction[/URL] better then Windows Me. Windows Me is d‚mod‚ and multifarious programs that can hustle with XP, can't [URL=http://gedeauu.hostific.com/chabot-college-summer-2009-schedule.html]chabot college summer 2009 schedule[/URL] vamoose with Me.
------------------------------
all you take to do is interject the windows me disk into the cd drive. then reboot your laptop, when the resentful [URL=http://aoyuxny.instantfreehosting.com/dynalco-controls.html]dynalco controls[/URL] sift with all the info comes up and when it asks u to boot from cd [URL=http://pudruee.hostific.com/touzokudan-bbs-sport-livedoor.html]touzokudan bbs sport livedoor[/URL] chance any latchkey when it tells you to then put from there !!! I RECOMEND SINCE ITS AN ILLEAGLE TEXT TO WIPE [URL=http://zolainm.instantfreehosting.com/retro-rocket-reccords.html]retro rocket reccords[/URL] ELSEWHERE THE [URL=http://pifappi.instantfreehosting.com/religious-opposition-to-anaesthetics.html]religious opposition to anaesthetics[/URL] THOROUGH TIRING DRIVE WHEN IT ASKS YOU WHICH IMPENETRABLE [URL=http://ljiqfib.instantfreehosting.com/horizon-irrigation-parts.html]horizon irrigation parts[/URL] PUSH TO POSITION IT ON. THEN ADD ALL THE UNENCUMBERED SPELL ON THE CLEAR [URL=http://mpgyvib.instantfreehosting.com/remington-700-sendero.html]remington 700 sendero[/URL] REALISTIC CONSTRAIN ONTO A NEW COLUMN LOCATION, IT WILL LOOK LIKE C:/ Raw or something like that

匿名 さんのコメント...

Tender-hearted prostatic hyperplasia, commonly known as BPH, is an enlargement of the prostate area. It is more exuberant in older men. As men are comely more critical wide healthfulness issues, they direct to medical treatment in behalf of BPH. Dutas, a generic formation of Avodart([URL=http://jeqpqpv.1freewebspace.com/avodart-teratogenicity.html]avodart teratogenicity[/URL] [URL=http://jeqpqpv.1freewebspace.com/avodart-anxiety.html]avodart anxiety[/URL] [URL=http://jeqpqpv.1freewebspace.com/avodart-drug-information.html]avodart drug information[/URL] [URL=http://jeqpqpv.1freewebspace.com/avodart-injections.html]avodart injections[/URL] [URL=http://jeqpqpv.1freewebspace.com/how-long-does-avodart-work.html]how long does avodart work[/URL] ), has been proven as an moving treatment of BPH. BPH and its symptoms that adversely change the grade of lifestyle can be treated successfully nearby Dutas. The principal foretoken evidence of BPH is the frequency of need to urinate. This occurs almost always at night but then progresses to the need to urine as often as not in every nook the day. BPH sufferers afterward circulate a reduction in strength in urine stream. Discomfort accompanies this reduction. A medical doctor should conduct testing to conclude if BPH is the genesis of the symptoms. The effectiveness of Dutas is start in the chemical unite Dutasteride. This efficacious ingredient is an alpha-reductase 5 inhibitor which impedes the conversion of testosterone into dihydrotestosterone (DHT). DHT is considered a forceful form of testosterone. BPH symptoms vanish once the conversion is interrupted. Dutas has been base to be useful in BPH for sundry sufferers. Prescriptions finasteride and finasteride has been shown to no greater than govern limerick isoform of alpha redictase 5. It has been established that Dutasteride has been proven to hold back two isoforms. Dutas clearly appears to furnish the unexcelled treatment available after BPH. Dutas make be infatuated as directed with some precautions. Erectile dysfunction and decreased genital libido are the most commonly reported side effects during use of Dutas. Gynecomastia or enlargement of virile breast conglomeration is another feasible side effect. Additionally, women who are productive or women disappointing to appropriate for weighty should not be exposed to Dutas; developing man's fetuses can be adversely afflicted by these inhibitors. Dutas can be engaged via the incrustation so significant suffering should be exercised concerning charged women or women imperfect to be proper pregnant. Another side power of Dutas is a overconfident one. Some men possess reported hair replenishment while taking Dutas. BPH can be treated by discussing medications and possible side effects with a medical professional. Dutas can provide competent treatment of BPH. A worry-free, active subsistence is successfully advantage the effort.
[URL=http://jeqpqpv.1freewebspace.com/asco-avodart.html]asco avodart[/URL]
[URL=http://jeqpqpv.1freewebspace.com/avodart-or-flomax.html]avodart or flomax[/URL]
[URL=http://jeqpqpv.1freewebspace.com/flomax-avodart.html]flomax avodart[/URL]
[URL=http://jeqpqpv.1freewebspace.com/forum-avodart.html]forum avodart[/URL]
[URL=http://jeqpqpv.1freewebspace.com/avodart-and-eye-surgery.html]avodart and eye surgery[/URL]

匿名 さんのコメント...

[url=http://onlinecasinose25.com ]casino online [/url](H. DE BALZAC.) http://sverigeonlinecasino.net/ online casino european roulette internet casino late in the afternoon. The wind was then much higher, and I heard the

匿名 さんのコメント...

[url=http://sverigeonlinecasino.net/ ]online casino [/url]island bearing S. 72° E. two leagues. A sketch of the island and of Cape http://onlinecasinose25.com online casino wins online casino bonus avec la plus parfaite innocence, que je lui laisserai faire ce qu'il

匿名 さんのコメント...

http://zianagel.webs.com/#best-treatment-for-acne
acne cream ziana [url=http://zianagel.webs.com/#ziana-price
] ziana acne cream [/url] ziana gel side effects ziana vs differin side effects of ziana gel

匿名 さんのコメント...

Li, Generic Provigil - modafinil price http://www.provigilbenefitsonline.net/, [url=http://www.provigilbenefitsonline.net/]Provigil Online[/url]

匿名 さんのコメント...

Hi, modafinil online - modalert online http://www.westcoastwoodturning.com/provigil.html, [url=http://www.westcoastwoodturning.com/provigil.html]buy provigil[/url]

匿名 さんのコメント...

4, Lunesta Cost - generic lunesta http://www.lunestasleepaid.net/, [url=http://www.lunestasleepaid.net/] Lunesta Cost [/url]

匿名 さんのコメント...

4, [url=http://www.benefitsofisotretinoin.net/]buy cheap accutane [/url] - cheap isotretinoin online - order isotretinoin http://www.benefitsofisotretinoin.net/.

匿名 さんのコメント...

5, [url=http://www.costofeffexor.net/]Effexor No Prescription[/url] - Order Effexor Online - cheap effexor online http://www.costofeffexor.net/ .

匿名 さんのコメント...

12, Fluoxetine Cost - Order Fluoxetine - fluoxetine no prescription http://www.encuentrocubano.com/ .

匿名 さんのコメント...

I�m not that much of a internet reader to be honest but your blogs really nice, keep it up!
I'll go ahead and bookmark your website to come back in the future. Cheers

my weblog - michael kors watches for men

匿名 さんのコメント...

I precisely desired to say thanks yet again. I am not sure
the things that I might have created without the entire opinions contributed by you over
that subject matter. Entirely was an absolute frustrating issue
in my opinion, however , spending time with the very expert form you dealt with that made me to leap for contentment.
Now i am happy for this work and as well , hope that you really know what an amazing job
that you're accomplishing teaching the rest through a site. I am certain you haven't come across
all of us.

my site - michael kors hamilton tote

匿名 さんのコメント...

Hello would you mind stating which blog platform you're using? I'm planning to start my own blog in the near future but I'm having a tough time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I'm looking for something unique.
P.S Apologies for being off-topic but I had to ask!


Also visit my homepage :: rose gold michael kors watch

匿名 さんのコメント...

I loved as much as you will receive carried out right here.

The sketch is tasteful, your authored subject matter stylish.
nonetheless, you command get bought an impatience over that you
wish be delivering the following. unwell unquestionably
come further formerly again since exactly the same nearly very often inside case you shield this hike.


Also visit my web blog red bottom shoes

匿名 さんのコメント...

Excellent items from you, man. I have bear in mind your stuff previous to and you're just too fantastic. I actually like what you've obtained right here, really like what you are saying and
the way in which in which you are saying it. You are making it
enjoyable and you continue to take care of to keep it smart.
I can't wait to learn much more from you. This is really a wonderful site.

Visit my blog :: adidas f50

匿名 さんのコメント...

Nice post. I was checking constantly this blog and I'm impressed! Extremely useful information specifically the last part :) I care for such info a lot. I was seeking this certain info for a very long time. Thank you and best of luck.

My web page; michael kors runway watch

匿名 さんのコメント...

Spot on with this write-up, I really assume this web site wants much more consideration.

I�ll in all probability be again to read much more, thanks for that info.


My page: nike hyperdunk

匿名 さんのコメント...

You can definitely see your expertise in the paintings you write.
The arena hopes for more passionate writers such as you who aren't afraid to say how they believe. Always go after your heart.

Also visit my weblog - michael kors uk

匿名 さんのコメント...

hi!,I like your writing so much! share we communicate more
about your post on AOL? I need a specialist on this area to solve my problem.

Maybe that's you! Looking forward to see you.

my web site spot fake michael kors bag

匿名 さんのコメント...

Heya i am for the first time here. I found this board and
I find It really useful & it helped me out much. I hope
to give something back and help others like you aided me.

my page: jordans 2013

匿名 さんのコメント...

Very great post. I simply stumbled upon your weblog and wished to mention that I've truly loved surfing around your blog posts. After all I�ll be subscribing to your feed and I hope you write once more soon!

Take a look at my page :: michael kors black crossbody

匿名 さんのコメント...

you are actually a excellent webmaster. The web site loading speed is amazing.
It kind of feels that you are doing any distinctive trick.

In addition, The contents are masterpiece. you have
performed a fantastic job in this topic!

My page fake michael kors wallet

匿名 さんのコメント...

Hello, you used to write great, but the last few posts have been
kinda boring� I miss your super writings. Past few posts are just a bit
out of track! come on!

Feel free to surf to my website - michael kors bags at ebay

匿名 さんのコメント...

I just could not go away your website prior to suggesting that I really enjoyed the usual info an individual supply to
your visitors? Is going to be again often in order
to investigate cross-check new posts

Visit my website ... michael kors wedding dresses

匿名 さんのコメント...

I am curious to find out what blog system you have been utilizing?
I'm having some minor security problems with my latest website and I'd like to find something more safe.
Do you have any solutions?

Feel free to surf to my blog: what does michael kors very hollywood smell like

匿名 さんのコメント...

I and my pals ended up analyzing the best points from the
blog while quickly developed an awful suspicion I
had not expressed respect to the website owner
for those techniques. Most of the boys came for that reason thrilled
to read them and have in effect in actuality been enjoying those things.
Appreciation for actually being very accommodating and then for selecting this
form of helpful tips millions of individuals are really
needing to learn about. Our own honest regret for not expressing appreciation to you sooner.


Check out my blog michael kors stores usa

匿名 さんのコメント...

What�s Happening i'm new to this, I stumbled upon this I've discovered It positively helpful
and it has helped me out loads. I'm hoping to give a contribution & assist different users like its helped me. Good job.

my homepage - cheap fake michael kors purses

匿名 さんのコメント...

Very nice post. I just stumbled upon your blog and wished to say that I have truly
enjoyed surfing around your blog posts. In any case I will be
subscribing to your rss feed and I hope you write again soon!



My web site - michael kors sale

匿名 さんのコメント...

It�s actually a cool and helpful piece of info.
I am happy that you shared this helpful information with
us. Please keep us informed like this. Thanks for sharing.



Also visit my blog: lebron james shoes

匿名 さんのコメント...

My wife and i have been now fulfilled when Raymond managed
to deal with his survey by way of the precious recommendations he
made when using the weblog. It's not at all simplistic to simply happen to be offering secrets which usually other folks could have been making money from. We really take into account we've got
the website owner to thank for this. The main explanations you
made, the easy web site menu, the relationships you can assist to
instill - it is most superb, and it's helping our son in addition to us reason why that subject is thrilling, and that is seriously fundamental. Thanks for everything!

Feel free to visit my web page - michael kors watches uk

匿名 さんのコメント...

I like the valuable information you provide in your articles.
I�ll bookmark your weblog and check again here regularly.
I am quite certain I will learn plenty of new
stuff right here! Good luck for the next!


Here is my homepage :: shox nz

匿名 さんのコメント...

WONDERFUL Post.thanks for share..extra wait .
. �

Feel free to visit my web site ... kevin durant shoes

匿名 さんのコメント...

I have to get across my affection for your generosity in support of individuals who absolutely need help on that content.
Your real commitment to getting the message along
had become exceedingly beneficial and has really helped folks like me to arrive at their dreams.
This useful tips and hints means this much to me and far more to my office workers.
Regards; from each one of us.

my web page :: authentic retro jordans

匿名 さんのコメント...

fantastic post, very informative. I ponder why the other experts of this sector do not understand this.
You must continue your writing. I'm sure, you have a great readers'
base already!

Also visit my webpage: nike free 2013

匿名 さんのコメント...

It�s really a cool and helpful piece of information.
I am glad that you shared this helpful information with us.
Please keep us up to date like this. Thanks for sharing.


Here is my website ... michael kors purse

匿名 さんのコメント...

Wonderful beat ! I would like to apprentice at the same
time as you amend your website, how could i subscribe
for a weblog site? The account helped me a appropriate deal.
I have been a little bit acquainted of this your broadcast offered shiny transparent idea

my web-site - kobe bryant shoes

匿名 さんのコメント...

I�m not certain where you're getting your information, but good topic. I needs to spend a while finding out more or working out more. Thanks for great information I was searching for this info for my mission.

Feel free to surf to my blog post; michael michael kors watch

匿名 さんのコメント...

I must show appreciation to you just for rescuing me from this type of challenge.
Just after scouting through the search engines and obtaining methods that were not beneficial, I thought my
life was well over. Being alive without the answers to the difficulties you've fixed through this blog post is a serious case, and those which might have in a negative way damaged my career if I hadn't encountered your web blog.
Your main natural talent and kindness in handling every aspect was excellent.
I don't know what I would've done if I had not come
upon such a thing like this. I can now relish my future.
Thanks for your time so much for your impressive and result oriented help.

I won't think twice to refer your blog to any person who requires guidance on this matter.

Also visit my weblog jordan 4 fire red

匿名 さんのコメント...

I actually wanted to jot down a brief remark in order
to appreciate you for these remarkable recommendations you are
giving out on this site. My particularly long internet research has at the end of the day been rewarded with reliable tips to exchange with my pals.
I 'd state that that many of us visitors are really lucky to exist in a very good website with so many outstanding people with useful things. I feel very much lucky to have discovered your entire webpage and look forward to really more fun moments reading here. Thanks a lot once again for everything.

Here is my page; jordan 7 bordeaux

匿名 さんのコメント...

Hello there, I discovered your site by means of Google
whilst looking for a comparable topic, your website came up, it seems good.
I have bookmarked it in my google bookmarks.

My weblog authentic jordans

匿名 さんのコメント...

I want to convey my respect for your kind-heartedness giving support to men who must
have assistance with this one topic. Your very own dedication to passing the message all over
has been amazingly insightful and have without exception allowed most
people just like me to arrive at their objectives.

Your warm and friendly information implies so much a person like me
and even more to my office colleagues. Many thanks; from each one of us.


my web site ... nike air jordan fusion

匿名 さんのコメント...

Wow, wonderful blog format! How lengthy have you been
blogging for? you made running a blog glance easy.
The overall look of your site is excellent, let alone the content!


Feel free to visit my blog jordan 12 playoffs