问题
I am writing C code, in which I am analyzing some data. I have set the program to handle only 100 data inputs. When it has more than 100 inputs, it is giving a segmentation fault. I want to create a way so that when the number of inputs is above 100 the user will be warned and the program will terminate. I know how to do it from the main function by simply return 0
, however I am multiple function calls away from main and it is difficult to do that even a return 0
in this function will keep it looping.
Is there any immediate way to terminate the entire program without being in main?
回答1:
The standard function exit
is what you are looking for:
Terminates the process normally, performing the regular cleanup for terminating processes.
First, all functions registered by calls to atexit are executed in the reverse order of their registration. Then, all streams are closed and the temporary files deleted, and finally the control is returned to the host environment.
The status argument is returned to the host environment.
It would be better though if you fixed the segfault error.
回答2:
You need to include the standard lib and then you can call exit wherever you want:
#include <stdlib.h>
...
exit(status);
where status is an integer representing the exit code. For what concern status: for the convention 0 is success, other values indicates an error status.
回答3:
You can also fprintf(stderr, ....)
and then call abort()
; this can be helpful if you want to debug later your bug.
But I believe you should recode your program so that size limitations are only given by available resources: so if you run your program on a much bigger computer (whatever that means) it could process more than 100 inputs.
回答4:
A slightly better thing to do might be to catch the segmentation fault with a signal handler, and have the signal handler raise a SIGSTOP signal.
That way your program stops, but stays in memory. You can then attach to it with a debugger and see the program in all its glory frozen in place at the point the SEGFAULT happened.
That can be useful for finding problems in long running programs that you aren't running inside a development IDE.
来源:https://stackoverflow.com/questions/7973583/how-can-i-immediately-close-a-program-in-c