Reputation: 3794
I have sort of a homework and it asks me to end the program gracefully without explicit termination such as calling exit() or killing the threads.
However I cannot think of any other methods than return 0
, so what are the methods to end a program gracefully?
Upvotes: 3
Views: 20634
Reputation: 446
No idea what they could mean with gracefully but my first idea was just a return 0.
Or exit(0)
Upvotes: 0
Reputation: 1507
Killing the threads is absolutely not a graceful way to terminate a program. I think what your instructor means is that all your parent
threads should wait on their child
threads before terminating themselves.
Ideally, an explicit call pthread_exit
from the main thread would ensure that all it's children continue running even after it exits. Refer to this link. But, the safest way to wait on your child threads before exiting is to use pthread_join
.
Nevertheless, exit(0)
is the graceful return for a process as such.
Upvotes: 5
Reputation: 7061
They may be referring to how you handle errors in lower-level routines. Rather than doing something like
printf("ERROR: couldn't initialize the claveman\n");
exit(1);
You would return from that routine (possibly printing the error message at that level or waiting to do it at a higher level like main()).
return CLAVEMAN_INITIALIZE_ERROR;
All your routines would return zero for success or non-zero error codes, up until the code in main was able to return either EXIT_SUCCESS or an error code indicating the failure.
Upvotes: 0
Reputation: 78923
I think you are missing to tell us that you have a multi-threaded program. I suppose that the the idea of gracefully terminating the program is meant to terminate all your threads by setting a flag or something like that. And then only to terminate your main
after all your threads have provably ended. The way you actually then terminate your main
is of lesser importance.
Upvotes: 1
Reputation: 29646
See my comment.
main
will by default return 0 in the lack of areturn 0;
statement.
See §5.1.2.2.3¶1 of the C99 standard.
If the return type of the
main
function is a type compatible withint
, a return from the initial call to themain
function is equivalent to calling theexit
function with the value returned by themain
function as its argument; reaching the}
that terminates themain
function returns a value of0
. If the return type is not compatible withint
, the termination status returned to the host environment is unspecified.
So, the following terminates gracefully although implicitly, distinguished from an explicit exit
or return
in main
.
main() { }
Upvotes: 0
Reputation: 53336
exit(0)
generally indicates that process (your program) terminated gracefully. In case of error it would exit(-1)
or some other error code.
Upvotes: 0