1207753Smm///////////////////////////////////////////////////////////////////////////////
2207753Smm//
3207753Smm/// \file       tuklib_exit.c
4207753Smm/// \brief      Close stdout and stderr, and exit
5207753Smm//
6207753Smm//  Author:     Lasse Collin
7207753Smm//
8207753Smm//  This file has been put into the public domain.
9207753Smm//  You can do whatever you want with this file.
10207753Smm//
11207753Smm///////////////////////////////////////////////////////////////////////////////
12207753Smm
13207753Smm#include "tuklib_common.h"
14207753Smm
15207753Smm#include <stdlib.h>
16207753Smm#include <stdio.h>
17207753Smm
18207753Smm#include "tuklib_gettext.h"
19207753Smm#include "tuklib_progname.h"
20207753Smm#include "tuklib_exit.h"
21207753Smm
22207753Smm
23207753Smmextern void
24207753Smmtuklib_exit(int status, int err_status, int show_error)
25207753Smm{
26207753Smm	if (status != err_status) {
27207753Smm		// Close stdout. If something goes wrong,
28207753Smm		// print an error message to stderr.
29207753Smm		const int ferror_err = ferror(stdout);
30207753Smm		const int fclose_err = fclose(stdout);
31207753Smm		if (ferror_err || fclose_err) {
32207753Smm			status = err_status;
33207753Smm
34207753Smm			// If it was fclose() that failed, we have the reason
35207753Smm			// in errno. If only ferror() indicated an error,
36207753Smm			// we have no idea what the reason was.
37207753Smm			if (show_error)
38207753Smm				fprintf(stderr, "%s: %s: %s\n", progname,
39207753Smm						_("Writing to standard "
40207753Smm							"output failed"),
41207753Smm						fclose_err ? strerror(errno)
42207753Smm							: _("Unknown error"));
43207753Smm		}
44207753Smm	}
45207753Smm
46207753Smm	if (status != err_status) {
47207753Smm		// Close stderr. If something goes wrong, there's
48207753Smm		// nothing where we could print an error message.
49207753Smm		// Just set the exit status.
50207753Smm		const int ferror_err = ferror(stderr);
51207753Smm		const int fclose_err = fclose(stderr);
52207753Smm		if (fclose_err || ferror_err)
53207753Smm			status = err_status;
54207753Smm	}
55207753Smm
56207753Smm	exit(status);
57207753Smm}
58