#include <sys/types.h><br />#include <sys/wait.h><br />#include <stdio.h><br />#include <signal.h><br />#include <unistd.h><br />#define MAXARGS 20<br />#define ARGLEN 100<br />main()<br />{<br />char *arglist[MAXARGS+1];<br />int numargs;<br />char argbuf[ARGLEN];<br />char *makestring();</p><p>numargs=0;<br />while(numargs<MAXARGS)<br />{<br />printf("Arg[%d]?",numargs);<br />if(fgets(argbuf,ARGLEN,stdin)&&*argbuf!='/n')<br />{<br />arglist[numargs++]=makestring(argbuf);<br />}<br />else<br />{<br />if(numargs>0)<br /> {<br /> arglist[numargs]=NULL;<br /> execute(arglist); //zhixing<br /> numargs=0;<br /> }<br /> }<br />}<br />}</p><p> execute(char *arglist[])<br /> {<br /> int pid,exitstatus;</p><p> pid=fork(); </p><p> switch(pid)<br /> {<br /> case -1:<br /> perror("fork failed!");<br /> exit(1);<br /> case 0:<br /> execvp(arglist[0],arglist);<br /> perror("execvp failed!");<br /> exit(1);<br /> default:<br /> while(wait(&exitstatus)!=pid)<br /> ;<br /> printf("child exit with status %d,%d/n",exitstatus>>8,exitstatus&0377);</p><p> }</p><p> }</p><p> char *makestring(char *buf)<br /> {<br /> char *cp,*malloc();</p><p> buf[strlen(buf)-1]='/0';<br /> cp=malloc(strlen(buf)+1);</p><p> if(cp==NULL)<br /> {<br /> fprintf(stderr,"no memory/n");<br /> exit(1);<br /> }<br /> strcpy(cp,buf);<br /> return cp;<br /> }<br />
這是來自unix/linux編程實踐教程上的例子。
除了linux的系統調用,值得注意的是還有一些細節問題。
比如對於fgets()函數接受的字串的處理。
char *fgets(char *s, int size, FILE *stream);
fgets() reads in at most one less than size characters from stream and
stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer.
A '/0' is stored after the last character in the buffer.
fgets 函數,從資料流讀取比size少1個字元,把他們儲存到s指向的緩衝區。如果遇到EOF或者換行,則
停止。如果是分行符號,分行符號也被儲存在緩衝區。'/0'被儲存在緩衝區的末尾.
所以在過程中要去掉擊鍵產生的'/n',通過makestring(char *buf)函數。