【发布时间】:2016-03-01 03:23:40
【问题描述】:
我正在创建一个简单的外壳。用户输入一个系统调用,对于用户输入的任何命令,我在子进程上分叉并调用 execvp。我进行了调试,似乎我传递给 execvp 的参数不正确。有人可以帮帮我吗,我是C的新手
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXLINE 80
int main(void){
char *args[MAXLINE/2 + 1];
char buf[MAXLINE/2 + 1];
int should_run = 1;
printf("Shell\n");
fgets(buf, MAXLINE,stdin);
buf[strlen(buf)-1] = '\0';
int i=0;
char *token;
token = strtok(buf," ");
while(token != NULL){
args[i++] = token;
token = strtok(NULL," ");
}
while(should_run){
if(strcmp(args[0],"exit") == 0){
should_run = 0;
break;
}
pid_t pid;
pid = fork();
//child process
if(pid == 0){
execvp(args[0],args);
}
else{
wait(0);
//Also how do I make it so that the program starts from top again, meaning it lets the user enter another system call
}
}
}
【问题讨论】:
-
execvp man page says this 关于第二个参数:“指针数组必须由 NULL 指针终止”。