【发布时间】:2017-07-21 07:51:02
【问题描述】:
我正在尝试制作一个 shell“bosh>”,它接收 Unix 命令并不断收到错误的地址错误。我知道我的代码会读取命令并解析它们,但由于某种原因,我无法让它们执行,而是出现“错误地址”错误。
#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;
}
【问题讨论】:
-
首先,图片中的狗不错。在
fgets读取的缓冲区中的最后一个字符之后存储一个终止空字节('\0')。所以你不必输入'\0'。 -
@TonyTannous 就是去掉换行符...(虽然它也不正确)。
-
在砍掉它之前,您需要检查最后一个字符是否确实是
'\n'。 -
我不确定,但我认为您将参数放入 commandArgs 的方式存在问题。您只存储第一个参数。最后一个参数必须为 NULL。
标签: c shell unix operating-system execvp