c - 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);
}
}
}
解决方案
在没有 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>
推荐阅读
- laravel - 添加 $table->engine = 'MyISAM' 后 Laravel 外键约束形成错误;
- javascript - 如果 ul 中的任何 li 有类
- maven - mvn pact:verify 不执行提供者状态,但 @State 代码从 IDE 执行
- sql-server - 错误“数据集是指不可用的共享数据集”是什么意思。意思是?
- python - 在 img.show 中显示倾斜
- c# - 带条件阅读文本
- powerbi - 如何将排序表中的第一个值转换为度量值?
- java - 在 Spring AOP 或 AspectJ 中拦截带注释的类和方法
- node.js - XState:等待调用函数的响应
- html - 在 HTML 中自动显示文本的最后一部分(从外部接收)