getCommandAndArgs 函数是新的,但函数中的代码是之前工作代码的副本。我试图允许命令行参数,然后继续运行 shell。我知道 fork 和 run 进程也可能在另一个函数中,但是在我知道为什么程序此时崩溃之前,我不想进一步前进。
char *cmd;
char *arguments[255];
char whitechars[] = " \n\t\r";
void getCommandAndArgs(char *tokLine) {
char *tok;
int i=0;
tok = tokLine;
while(tok != NULL) {
if(strcmp(tok, "exit")==0) {
printf("Thank you for using myshell!\n");
exit(0);
}
if(i==0) { cmd = tok; }
arguments[i] = tok;
tok = strtok(NULL, whitechars);
i++;
}
arguments[i]=NULL;
}
int main(int argc, char *argv[]) {
char *line, *tok;
int status=0;
int i;
pid_t pid;
if(argc > 1) {
line = *argv;
tok = strtok(line, whitechars);
tok = strtok(NULL, whitechars);
getCommandAndArgs(tok);
pid = fork();
if(pid == 0) {
execvp(cmd, arguments);
//oh $h!t message
fprintf(stderr, "What is this: %s\n", arguments[0]);
exit(0);
}
else {
waitpid(pid, &status, 0);
if(status !=0) {
fprintf (stderr, "error: %s exited with status code %d\n", arguments[0], status);
}
}
}
while((line = readline("myShell: ")) != NULL) {
if(strcmp(line, "")==0) {
continue;
}
tok = strtok(line, whitechars);
getCommandAndArgs(tok);
pid = fork();
if(pid == 0) {
execvp(cmd, arguments);
//oh $h!t message
fprintf(stderr, "What is this: %s\n", arguments[0]);
exit(0);
}
else {
waitpid(pid, &status, 0);
if(status !=0) {
fprintf (stderr, "error: %s exited with status code %d\n", arguments[0], status);
}
}
free(line);
}
printf("\nThank you for using myshell!\n");
return 0;
}