当我的代码看起来像这样时,我可以完美地运行ls -la。
char * ls_args[3] = {"ls","-la",NULL};
pid_t c_pid, pid;
int status;
c_pid = fork();
if (c_pid == 0){
/* CHILD */
printf("Child: executing lsn");
//execute ls
execvp( ls_args[0], ls_args);
//only get here if exec failed
perror("execve failed");
}else if (c_pid > 0){
/* PARENT */
if( (pid = wait(&status)) < 0){
perror("wait");
_exit(1);
}
printf("Parent: finishedn");
}else{
perror("fork failed");
_exit(1);
}
}
但是当我这样做时,它不起作用并且非常令人困惑,因为当我从该行中读取 ls 并将其传递给 execvp 时,它与 ls_args[0] 不是一回事吗? 但它不是这样工作的。 任何帮助都会很棒,谢谢
arguments[count] = NULL;
pid_t c_pid, pid;
int status;
c_pid = fork();
if (c_pid == 0){
/* CHILD */
printf("Child: executing lsn");
//execute ls
execvp( arguments[0], arguments);
//only get here if exec failed
perror("execve failed");
}else if (c_pid > 0){
/* PARENT */
if( (pid = wait(&status)) < 0){
perror("wait");
_exit(1);
}
printf("Parent: finishedn");
}else{
perror("fork failed");
_exit(1);
}
}
参数[0]中的是"ls"。 同样,当我检查每个长度并比较它们时,只要其中的字符串是同一件事。
我的完整代码
int main(){
char *line;
int quit = 1;
char **arguments;
char *directory;
int count = 0;
char *comand = "ls";
int done = 1;
printf("nnnnnnnLinux Shell: nCreated by: Zach Adamsnn");
//while this is one it will keep looping
while(1){ //will run until user enters quit
done = 1;
count = 0;
print_shell_name();
line = (char *)malloc(sizeof(line));
arguments = (char **)malloc(sizeof(char*));
line = fgets(line,MAX,stdin);
quit = strncmp(line,"quit",4);
if(quit == 0)
exit(0);
int i = 0; //parsing line
char *p = strtok(line, " "); //will save the string up to the token entered
free(line);
while(p!= NULL){
arguments[i++] = p; //putting the command or argument into an array of arguments
p = strtok(NULL," "); //null is a pointer to the first argument and continues to scan where prev call ends until it gets to token again
count++;
}
p = strtok(arguments[count-1], "n"); //get the new line character off of the end
arguments[count-1] = p;
if((strncmp(arguments[0],"cd",2)==0) || (strncmp(arguments[0],"clr",3)==0) //run internal commands
|| (strncmp(arguments[0],"dir",3) ==0) || (strncmp(arguments[0],"environ",7)==0) || (strncmp(arguments[0],"echo",4)==0)
|| (strncmp(arguments[0],"help",4)==0) || (strncmp(arguments[0],"pause",5)==0)){
execute(arguments,count); //execute internal commands
}else if(arguments[0] == NULL){
printf("NULL arg");
}else{
//char * ls_args[3] = {"ls","-la",NULL};
arguments[count] = NULL;
pid_t c_pid, pid;
int status;
c_pid = fork();
if (c_pid == 0){
/* CHILD */
printf("Child: executing lsn");
//execute ls
execvp( arguments[0], arguments);
//only get here if exec failed
perror("execve failed");
}else if (c_pid > 0){
/* PARENT */
if( (pid = wait(&status)) < 0){
perror("wait");
_exit(1);
}
printf("Parent: finishedn");
}else{
perror("fork failed");
_exit(1);
}
}
free(arguments);
}
返回 0;
}
此代码会销毁您strtok()
使用的line
变量:
char *p = strtok(line, " "); //will save the string up to the token entered
free(line);
当您致电时
strtok(NULL," ")
后来,strtok()
仍在尝试解析line
,它已被释放。