如何创建因段错误而崩溃但没有核心转储的程序

发布于 2025-01-19 02:45:39 字数 741 浏览 3 评论 0原文

我目前正在用 C 编写一个类似 UNIX 的 shell,为了测试我的 shell,我需要创建一个程序来创建分段错误,但不会打印Core Dumped

我已经编写了一个执行段错误的程序(类似于 int *a = 0; *a = 3;),当我运行它时,终端打印 Segmentation Failure (Core Dumped)< /代码>。

我应该编写什么代码,或者应该使用什么命令,以便我的终端在运行时仅打印 Segmentation Failure,而不是 Segmentation Failure (Core Dumped)

编辑: 我不仅希望缩短输出,还想创建一个在崩溃时不创建核心转储的程序(例如,当我在退出状态上使用 WCOREDUMP 宏时)由waitpid给出的程序,它返回1。)

解决方案: 我编写了一个仅引发 SIGUSR1 信号的程序;通过运行它,我遇到了“崩溃”,但没有打印 (core dumped) - 这正是我正在寻找的。

代码,以防有人需要:

#include <signal.h>

int main()
{
    raise(SIGUSR1);
    return 0;
}

终端输出: 用户定义信号1

I am currently writing in C a UNIX-like shell, and in order to test my shell, I need to create a program that creates a segmentation fault, but without Core Dumped being print.

I already wrote a program that does a segfault (something like int *a = 0; *a = 3;), and when I run it the terminal print Segmentation Fault (Core Dumped).

What code should I write, or what command should I use, in order for my terminal to only print Segmentation Fault when I run it, and not Segmentation Fault (Core Dumped) ?

Edit:
I don't only want the output to be shortened, I also want to create a program that does not create a core dump when it crashes (such that when I use the WCOREDUMP macro on the exit status of the program, given by waitpid, it returns 1.)

Solution:
I made a program that only raise the SIGUSR1 signal ; By running it, I get a 'crash' but without (core dumped) being print - which is what I am looking for.

Code, in case someone needs it:

#include <signal.h>

int main()
{
    raise(SIGUSR1);
    return 0;
}

Terminal output:
User defined signal 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

卖梦商人 2025-01-26 02:45:39

在本例中,您可能会弄乱 signal.h

`

#include <signal.h>    

void sig_func(int sig)
{
    exit(1);
}

int main (void)
{
    signal(SIGSEGV, sig_func); // sets a new signal function for SIGSEGV
    raise(SIGSEGV); // causes the signal function to be called

    return 0;
}

`

,它应该以 1 退出,不打印任何内容,将 sig_func 更改为您需要的任何内容。

顺便说一句......使用信号,您可以完全覆盖该信号发出时发生的情况。如果您摆脱了退出调用,程序将继续运行,无论其构成什么未定义的行为。

You could mess with signal.h

`

#include <signal.h>    

void sig_func(int sig)
{
    exit(1);
}

int main (void)
{
    signal(SIGSEGV, sig_func); // sets a new signal function for SIGSEGV
    raise(SIGSEGV); // causes the signal function to be called

    return 0;
}

`

in this example, it should exit with 1, printing nothing, change the sig_func to whatever you need.

By the way... With signal you're completely overwriting what happens when that signal is raised. If you got rid of the exit call the program would keep running, with whatever undefined behavior that constitutes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文