在我的C shell上实现一个出口函数



我一直在尝试在我的C shell上实现一个退出命令。我尝试过fork-exec方法,因为它是一个系统调用。当我运行程序时,它会提示输入stdin,当我输入"stdin"时;退出";它返回一个"0";分段故障(堆芯倾倒(";错误我做错了什么?

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#define ARGVMAX 100
#define LINESIZE 1024
#define EXITCMD "exit"
//makeargv - builds an argv vector from words in a string
int makeargv(char *s, char *argv[ARGVMAX]) {
int ntokens = 0;
if (s == NULL || argv == NULL || ARGVMAX == 0)
return -1;
argv[ntokens] = strtok(s, " tn");
while ((argv[ntokens] != NULL) && (ntokens < ARGVMAX)) {
ntokens++;
argv[ntokens] = strtok(NULL, " tn");
}
argv[ntokens] = NULL; // it must terminate with NULL
return ntokens;
}
void prompt() {
printf("sish> ");
fflush(stdout); //writes the prompt
}
/******  MAIN  ******/
int main() {
char line[LINESIZE];
int wstatus;
while (1) {
prompt();
if (fgets(line, LINESIZE, stdin) == NULL)
break;
// TODO:
if(fgets(line, LINESIZE, strcmp(stdin, EXITCMD )) == 0)
return 0;
signal(SIGINT, SIG_DFL);
if (fork() == 0) exit(execvp(line[0], line));
{
signal(SIGINT, SIG_IGN);
}
wait(&wstatus);
if(WIFEXITED(wstatus))
printf("<%d>", WEXITSTATUS(wstatus));
}
return 0;
}

在检查和清理代码后,我终于能够实现exit命令。

代码如下:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>

#define ARGVMAX 100
#define LINESIZE 1024
#define EXITCMD "exit"

//makeargv - build an argv vector from words in a string
int makeargv(char *s, char *argv[ARGVMAX]) {
int ntokens = 0;
if (s == NULL || argv == NULL || ARGVMAX == 0)
return -1;
argv[ntokens] = strtok(s, " tn");
while ((argv[ntokens] != NULL) && (ntokens < ARGVMAX)) {
ntokens++;
argv[ntokens] = strtok(NULL, " tn");
}
argv[ntokens] = NULL; // it must terminate with NULL
return ntokens;
}



void prompt() {
printf("C Shell >> ");
fflush(stdout); //writes the prompt
}
/******  MAIN  ******/
int main() {
char line[LINESIZE];                            

while (1) {                                     
prompt();                                   
if (fgets(line, LINESIZE, stdin) == NULL)   
break;                                  
// TODO:
char *p = strchr(line, 'n');           

if (p)                                      
*p = 0;                                 
if(strcmp(line, "exit") == 0)               
break;                                  
char *args[] = {line, (char*) 0};

int pid = fork();                           
if (pid == 0){                               
execvp(line, args);                 
perror("Command Error!");           
exit(1);                            
} else {                                    
wait(NULL);                             
}
return 0;
}
return 0;
}

最新更新