【发布时间】:2015-05-20 18:45:29
【问题描述】:
所以,我正在用 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 &)时,它给了我一个段错误。不知道为什么,谁能帮帮我?
Execute 是一个接受命令的函数,fork() 然后在子进程中使用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;
}
【问题讨论】:
-
r[size-1] = NULL;吓到我了...sizesize = parser(input, r);是什么 -
你有崩溃的回溯吗?
-
在崩溃前是否打印了“背景”会很有趣...
-
@polarysekt 编辑了问题,因此它回答了您的问题,但简而言之:我使用
size查看命令数量,如果有,请删除&。此外,background被打印出来。 -
我错过了 r 的类型。
char * r[40]r[size-1][0] = '\0';会工作吗?
标签: c shell segmentation-fault signals