سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

exit(0) generally indicates that process (your program) terminated gracefully. In case of error it would exit(-1) or some other error code.

See my comment.

main will by default return 0 in the lack of a return 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 with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, 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() { }

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.

No idea what they could mean with gracefully but my first idea was just a return 0.

Or exit(0)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top