我想做一个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''在切断它之前。 –