Home > other >  How to create a program that crashes with a segfault, but without core dump
How to create a program that crashes with a segfault, but without core dump

Time:04-07

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

CodePudding user response:

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.

  • Related