hi everyone.

my program uses an infinite loop & runs forever.
i want to run some codes when i decide to stop the program using CTRL-C.

Is this possible ? Please advise me.

thanks

There isn't a standard way to do it -- depends on the operating system. You might try calling onexit(), but it may not get called when Ctrl-C is hit.

I'm not exactly sure what you mean, but as CTRL-C is used to terminate your program I doubt any code will be allowed to run.

You could try signal():

#include <stdio.h>
#include <signal.h>

void cleanup(int unused) {
    printf("Cleaning up\n");
    exit(-1);
}

int main() {
    signal(SIGINT, cleanup);
    for (;;) /* Ctrl-C to exit */
        ;
}

As nucleon illustrated above it will depend on the operating system. His code is *nix only and possily MAC. For MS-Windows, see this article

thanks nucleon & Ancient Dragon.

I modified the way the program will be running.It will run in the background so no output will be visible to the console.

I want to use the kill command & achieve same result.
Plz advise me what i need to modify.

thanks.

you must be running *nix because MS-Windows doesn't have such a command. kill -9 123 where 123 is the pid of the running process.

Thanks for advising Ancient Dragon.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.