有人可以請建議這個程序有什麼問題。我試圖通過在這裏創建一個子進程來實現類似shell的功能。在給出一個命令有單個詞如ls
或pwd
它的作品,但命令與多個詞如ls -lrt
或who am i
不起作用。有一些愚蠢的錯誤,我正在做但無法調試。使用unix系統調用在C程序中實現類似shell的功能
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <wait.h>
#include <errno.h>
#include <sys/types.h>
#include <cstdlib>
#define BUFSIZE 200
#define ARGVSIZE 40
#define DELIM "\n\t\r"
int main()
{
int i,n;
char buf[BUFSIZE + 1] ;
char * str = "Shell > ";
char * clargs[ARGVSIZE] ;
int returnstatus;
for(;;)
{
n = 1;
write(STDOUT_FILENO,str,strlen(str));
read(STDIN_FILENO,buf,BUFSIZE);
if(!strcmp(buf,"exit\n"))
{
perror("exit");
exit(20);
}
clargs[0] = strtok(buf,DELIM);
while((clargs[n] = strtok(NULL,DELIM)) != NULL)
n++;
clargs[n] = NULL;
switch(fork())
{
case 0:
if((execvp(clargs[0],&clargs[0])) < 0)
exit(200);
default:
wait(&returnstatus);
printf("Exit status of command : %d\n",WEXITSTATUS(returnstatus));
for(int i =0; i <= n;i++)
clargs[i] = "\0";
for(int i =0; i < BUFSIZE+1;i++)
buf[i] = '\0';
}
}
return 0;
}
你是什麼意思的「不工作」? – Thomas
@Thomas ...它不適用於具有多個單詞如「ls -lrt」或說「我是誰」的命令 –
「不工作」以何種方式?怎麼了? –