gpt4 book ai didi

c - 用 c 编写基本 shell 时使用信号处理程序时出现段错误

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

所以,我正在用 C 编写一个基本 shell,并且需要有信号处理程序。

终止后台进程的检测应通过两种机制来实现,其中一种机制选择应在编译时进行编译。这些机制是通过子进程发送的信号进行普通轮询和检测。用户应该能够通过定义宏来选择使用哪种机制SIGDET=1在编译时通过信号检测到终止。如果 SIGDET 未定义或等于 0,则应通过轮询检测终止。

我需要使用 gcc -pedantic -Wall -ansi -O4 进行编译当我使用 cc -pedantic -Wall -ansi -O4 main.c -o shell -DSIGDET=1 && ./shell 调用我的程序时,然后运行一个简短的后台进程(例如, sleep 2 & ),它给了我一个段错误。我不知道为什么,有人可以帮助我吗?

执行是一个接受命令的函数,fork()然后在 child 中使用 execvp .

编辑:有几个问题:

parser()返回输入的命令数量,例如 sleep 3 &返回 3。r[size-1] = NULL删除最后一个命令,但前提是它是 & 。那是因为我不想发送它来执行,我只需要知道它应该在后台运行。

编辑:打印输出:

background输入命令 & 后立即。然后它打印出 OUTSIDE LOOP消息,然后打印段错误然后退出。

编辑:使用 -g 标志并运行 gdb

我运行调试,得到以下结果:

>: sleep 2 &
background
>: OUTSIDE LOOP: 11661 with this status: 0
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7aa0ad9 in strtok () from /lib/x86_64-linux-gnu/libc.so.6

我没有对 strtok() 做任何奇怪的事情,它只在解析器中使用,如下所示:

int parser(char * input, char ** r)
{
int i = 0;
char *tokens = strtok(input, DELIM);
/* char r[40]; */

while(tokens)
{
r[i] = tokens;
tokens = strtok(NULL, DELIM);
i++;
}
r[i] = NULL;
return i;
}

这是我的代码(不包括解析和执行函数等):

#define _POSIX_SOURCE
#include <stdio.h>
#include <string.h>
#include <unistd.h> /* for getcwd */
#include <stdlib.h> /* for malloc */
#include <signal.h>
#include "functions.h"
#include "textfunc.h"
#include "textfunc.c"
#include "functions.c"

#define MAX_LENGTH 80
#define DELIM " \n\r\t"

typedef void (*sighandler_t)(int);
sighandler_t signal(int signum, sighandler_t handler);

void sig(int signal)
{
int status;
pid_t pid = waitpid(-1, &status, WNOHANG);
printf(" OUTSIDE LOOP: %d with this status: %d\n", pid, status);
}

int main()
{
char *input;
char * r[40];
int size;

signal(SIGINT, SIG_IGN); /* */

#if SIGDET==1
signal(SIGCHLD, sig);
#endif

while(1)
{
int bg = -1;

#if SIGDET!=1
int status;
pid_t pid = waitpid(-1, &status, WNOHANG);
if(pid > 0)
printf("INSIDE LOOP: %d with this status: %d\n", pid, status);
#endif

prompt();

input = readInput();
size = parser(input, r);

if(r[0] == NULL)
continue;
else if(strcmp("&", r[size-1]) == 0)
{
printf("background\n");
r[size-1] = NULL;
bg = 0;
}
if(strcmp("exit", r[0]) == 0)
{
kill(0, SIGKILL);
}
else if(strcmp("cd", r[0]) == 0)
changedir(r[1]);
else if(strcmp("checkEnv", r[0]) == 0)
checkenv(r);
else
{
execute(&input, r, bg);
}
}
return 0;
}

最佳答案

您可能想阅读“signal()”的手册页,其中部分内容是:

The behavior of signal() varies across UNIX versions, and has also var‐ ied historically across different versions of Linux. Avoid its use: use sigaction(2) instead.

请注意有关使用 sigaction() 而不是 signal() 的部分

关于c - 用 c 编写基本 shell 时使用信号处理程序时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30357958/

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