简体   繁体   中英

Restart program in C

Hi I have a program written in C. I have global variables, arrays, dynamic variables and also arrays etc... I send SIGHUP to my program and in handler I clean up the dynamic memory.And I want to restart my program with HUP.IS there a way to restart the program in c?. I want to exit and return from main in order to clean the memory that are handled by the static arrays in main and restart main.

Hi again. I edited the signal handler and added the execv in the handler. in the handler i have 2 functions. first is clean_up(); that cleans the dynamic arrays and the second is execv(). after sending HUP,first clean_up runs and then execv. but after a small time i have seg fault. but ,when i dont call the clean_up func, then it works fine?is there a problem in cleanup?. but cleanup works fine with other signals,termination signal for example

And a question for execv?.Does not it start the new program from main?.When I call execv, it does not start from main again

Since you are on linux I think this is the cleanest way:

int main(int argc, char **argv) {
    /* your program here */

    /* if you want to restart call this */
    if (execv(argv[0], argv)) {
        /* ERROR, handle this yourself */
    }

    return 0;
}

I'm assuming you're using some form of unix. There is an answer to a similar question here . That code is just rereading the config files, which is what people expect to happen when you sighup, rather than an actual restart. That said, if you want to restart, just replace the load_config() call with an exec. There are a few exec calls to choose from, so look at the manpages for exec or the execve to choose which one you want. You'll be passing the environment and argv pointers from the parent process to preserve them when you exec.

For whatever it's worth, I don't really see why you want to clean static arrays if you're going to restart the program and presumably just reinitialize them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM