我想做一個shell「bosh>」,它需要在Unix命令並不斷收到錯誤的地址錯誤。我知道我的代碼讀取命令並解析它們,但出於某種原因,我無法讓它們執行,而是出現「錯誤地址」錯誤。與execvp錯誤的地址錯誤
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
#define MAX_LINE 128
#define MAX_ARGS 10
int main(){
pid_t pid;
char command[MAX_LINE]; /*command line buffer*/
char *commandArgs[MAX_ARGS]; /*command line arg*/
int i;
char *sPtr=strtok(command," ");
int n=0;
printf("bosh>");
fgets(command, MAX_LINE-1,stdin);
command[strlen(command)-1]='\0';
while(strcmp(command,"quit")!=0)
{
n=0;
sPtr=strtok(command," ");
while(sPtr&&n<MAX_ARGS)
{
sPtr=strtok(NULL," ");
n++;
}
commandArgs[0]=malloc(strlen(command)+1);
strcpy(commandArgs[0],command);
if(fork()==0)
{
execvp(commandArgs[0],commandArgs);
perror("execvp failed");
exit(2);
}
pid=wait(NULL);
printf("%s",">");
fgets(command, MAX_LINE-1,stdin);
command[strlen(command)-1]='\0';
}
printf("Command (%d) done\n", pid);
return 0;
}
首先,圖片中的好狗。 終止空字節('\ 0')存儲在由'fgets'讀取的緩衝區中的最後一個字符之後。所以你不需要放一個''\'0'。 –
@TonyTannous即剝離換行符(儘管它也不正確)。 –
你想檢查最後一個字符確實是一個''\ n''在切斷它之前。 –