首页 > 解决方案 > C中的Minishell“分段错误,核心转储”错误

问题描述

以下是我的 shell 代码的一部分。该代码有效,但是当我尝试输入“ls”之类的命令时,我的程序崩溃了。我认为这是一个正确的错误,因为我尝试访问“/bin”文件。


void lecture (char cmd1[], char *argv[]){ 
    int x = 0;
    char ligne [1024];
    char *aux [100], *pch;
    while (1){
        int mot = fgetc (stdin);
        ligne[x] = (char) mot;
        x++;
        if (mot == (int)'\n') break;
    }    
    aux[0] = strtok (ligne, " \n");
    strcpy(cmd1,aux[0]); 
    for (int i = 1; i <= 1024; i++){
        argv[i+1] = aux[i];
    }
}

int main(){
    char cmd1 [100];
    char cmd2 [100];
    int a = 10;
    char *argv [20];
    char *envp[] = {(char *) "PATH=/bin", 0};
    while (1){
        affichage();
        lecture (cmd2, argv); 
        printf("Test");
        if ( fork() != 0){
            printf("Err");
            wait (NULL);
        }else{
            strcpy(cmd1, "/bin/");
            strcat(cmd1, cmd2);
            execve(cmd1, argv, envp);
        }
    }    
}

标签: cshellcoredump

解决方案


在没有 SIGSEGV 的情况下,我通过以下修改得到了一些工作lecture

for (int i = 0; i < 20; i++){

例子:

 ./ms
ls
����: cannot access 'ls': No such file or directory
TestErr
...

但是你也可以像我在调试模式下编译一样调试它:

gcc -o ms -g -Wall -pedantic -Wextra -std=c11 ms.c

gdb用于检查 SIGSEGV 发生的位置。

请注意,您应该发布带​​有完整代码的https://stackoverflow.com/help/minimal-reproducible-example(这里我们缺少affichage)和

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

推荐阅读