File: ErrorContext.cpp

package info (click to toggle)
pbzip2 1.1.8-1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 304 kB
  • sloc: cpp: 4,349; makefile: 84
file content (92 lines) | stat: -rw-r--r-- 1,813 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* 
 * File:   ErrorContext.cpp
 * Author: Yavor Nikolov
 * 
 * Created on 29 October 2011, 18:14
 */

#include "pbzip2.h"
#include "ErrorContext.h"

#include <cstring>
#include <cerrno>

namespace pbzip2
{

ErrorContext * ErrorContext::_instance = 0;
pthread_mutex_t ErrorContext::_err_ctx_mutex = PTHREAD_MUTEX_INITIALIZER;

ErrorContext * ErrorContext::getInstance()
{
	pthread_mutex_lock( &_err_ctx_mutex );

	if ( ErrorContext::_instance == NULL )
	{
		_instance = new(std::nothrow) ErrorContext;

		if ( _instance == NULL )
		{
			fprintf( stderr, "pbzip2: *ERROR: Can't initialize error context - out of memory!\n" );
		}
	}

	pthread_mutex_unlock( &_err_ctx_mutex );

	return _instance;
}

void ErrorContext::printErrnoMsg( FILE * out, int err )
{
	if ( err != 0 )
	{
		fprintf( out, "pbzip2: *ERROR: system call failed with errno=[%d: %s]!\n",
			err, std::strerror( err ) );
	}
}

void ErrorContext::syncPrintErrnoMsg( FILE * out, int err )
{
	pthread_mutex_lock( &_err_ctx_mutex );
	printErrnoMsg( out, err );
	pthread_mutex_unlock( &_err_ctx_mutex );
}

void ErrorContext::printErrorMessages( FILE * out )
{
	pthread_mutex_lock( &_err_ctx_mutex );
	
	printErrnoMsg( out, _first_kernel_err_no );
	printErrnoMsg( out, _last_kernel_err_no );
	
	pthread_mutex_unlock( &_err_ctx_mutex );
}

void ErrorContext::saveError()
{
	int newerr = errno;
	
	pthread_mutex_lock( &_err_ctx_mutex );
	
	if ( newerr != 0 )
	{
		int & err_ref = ( _first_kernel_err_no == 0 )
						? _first_kernel_err_no
						: _last_kernel_err_no;
		
		err_ref = newerr;
	}

	_last_kernel_err_no = errno;

	pthread_mutex_unlock( &_err_ctx_mutex );
}

void ErrorContext::reset()
{
	pthread_mutex_lock( &_err_ctx_mutex );
	_first_kernel_err_no = _last_kernel_err_no = 0;
	pthread_mutex_unlock( &_err_ctx_mutex );
}

} // namespace pbzip2