gpt4 book ai didi

c - 为什么我的 C 程序第二次崩溃?

转载 作者:行者123 更新时间:2023-11-30 15:20:11 25 4
gpt4 key购买 nike

我为一个简单的 shell 编写了一个小程序作为学习 C 的练习。不幸的是,该程序在第二次调用时崩溃了。

$ ./a.out 
miniShell>> ls
ls
a.out digenv.c~ miniShell.c~ test
digenv digenv.c.orig miniShell.c.orig testshell.c
digenv2.c digenv.old.c README.md testshell.c~
digenv2.c~ LICENSE smallshell.c testshell.c.orig
digenv.c miniShell.c smallshell.c.orig
Child exited
miniShell>> ls
ls
Segmentation fault (core dumped)

你能帮我解决这个问题吗?代码是:

#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <stdarg.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
int mystrcmp(char const *, char const *);


void err_syserr(char *fmt, ...)
{
int errnum = errno;
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (errnum != 0)
fprintf(stderr, "(%d: %s)\n", errnum, strerror(errnum));
exit(EXIT_FAILURE);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_LEN 1024
#define BUFFERSIZE 1024
int main() {
char line[BUFFER_LEN];
char* argv[100];
char* path= "/bin/";
char progpath[20];
int argc;
size_t length;
char *token;
int i=0;
int pid;
while(1) {

printf("miniShell>> ");

if(!fgets(line, BUFFER_LEN, stdin)) {
break;
}
length = strlen(line);
if (line[length - 1] == '\n') {
line[length - 1] = '\0';
}
if(strcmp(line, "exit")==0) {
break;
}


token = strtok(line," ");

while(token!=NULL) {
argv[i]=token;
token = strtok(NULL," ");
i++;
}
argv[i]=NULL;

argc=i;
for(i=0; i<argc; i++) {
printf("%s\n", argv[i]);
}
strcpy(progpath, path);
strcat(progpath, argv[0]);

for(i=0; i<strlen(progpath); i++) {
if(progpath[i]=='\n') {
progpath[i]='\0';
}
}
pid= fork();

if(pid==0) {
execvp(progpath,argv);
fprintf(stderr, "Child process could not do execvp\n");

} else {
wait(NULL);
printf("Child exited\n");
}

}
return (0);
}

int mystrcmp(char const *p, char const *q)
{
int i = 0;
for(i = 0; q[i]; i++)
{
if(p[i] != q[i])
return -1;
}
return 0;
}

int cd(char *pth) {
char path[BUFFERSIZE];
char cwd[BUFFERSIZE];
char * return_value;
int other_return;
strcpy(path,pth);

if(pth[0] != '/')
{
return_value = getcwd(cwd,sizeof(cwd));
strcat(cwd,"/");
strcat(cwd,path);
other_return = chdir(cwd);
} else {
other_return = chdir(pth);
}
printf("Spawned foreground process: %d\n", getpid());
return 0;
}

该程序的行为应该像一个小 shell,能够接受任意命令并执行它们(不使用系统调用)。你能帮我吗?

最佳答案

该问题是由于在顶级 while 循环开始时 i 的值未重置为 0 引起的。

添加行

  i = 0;

就在

之前
  printf("miniShell>> ");                    

一切都应该很好。

关于c - 为什么我的 C 程序第二次崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30147386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com