34
35:- module(c_error,
36 [ posix_status/1, 37 posix_status/4, 38 posix_ptr_status/1, 39 posix_ptr_status/4, 40 posix_raise_error/0,
41 posix_raise_error/3 42 ]). 43:- use_module(ffi).
68cpp_const('ENOENT').
69cpp_const('EPERM').
70cpp_const('EACCES').
71cpp_const('ENOMEM').
72
73:- c_import("#include <string.h>
74 #include <errno.h>",
75 [ libc ],
76 [ strerror(+int, [string]) ]).
87posix_status(Status) :-
88 ( Status >= 0
89 -> true
90 ; posix_raise_error
91 ).
92
93posix_status(Status, Op, Type, Arg) :-
94 ( Status >= 0
95 -> true
96 ; posix_raise_error(Op, Type, Arg)
97 ).
105posix_ptr_status(Ptr) :-
106 c_is_nil(Ptr),
107 !,
108 posix_raise_error.
109posix_ptr_status(_).
110
111posix_ptr_status(Ptr, Op, Type, Arg) :-
112 c_is_nil(Ptr),
113 !,
114 posix_raise_error(Op, Type, Arg).
115posix_ptr_status(_, _, _, _).
125posix_raise_error :-
126 c_errno(Errno),
127 strerror(Errno, String),
128 throw(error(posix_error(Errno, String), _)).
129
130posix_raise_error(Op, Type, Arg) :-
131 c_errno(Errno),
132 strerror(Errno, String),
133 posix_exception_context(Op, Type, Arg, String, Context),
134 ( posix_exception(Errno, Op, Type, Arg, Context)
135 -> true
136 ; throw(error(posix_error(Errno, String), Context))
137 ).
138
139posix_exception_context(Op, Type, Arg, String, Context) :-
140 Context = context(_Stack, posix(Op, Type, Arg, String)).
141
142posix_exception('ENOENT', _Op, Type, Arg, Context) :- !,
143 throw(error(existence_error(Type, Arg), Context)).
144posix_exception('EACCES', Op, Type, Arg, Context) :- !,
145 throw(error(permission_error(Op, Type, Arg), Context)).
146posix_exception('EPERM', Op, Type, Arg, Context) :- !,
147 throw(error(permission_error(Op, Type, Arg), Context)).
148posix_exception('ENOMEM', _Op, _Type, _Arg, Context) :- !,
149 throw(error(resource_error(memory), Context)).
150
151
152 155
156:- multifile
157 prolog:message_context//1,
158 prolog:error_message//1. 159
160prolog:message_context(context(_, posix(Op, Type, Arg, _String))) -->
161 { nonvar(Op) },
162 [ ' in ~w on ~p ~p'-
163 [Op, Type, Arg] ].
164prolog:error_message(posix_error(Errno, String)) -->
165 [ '~p (errno=~p)'-[String, Errno] ]
C interface error handling
This module provides common routines to map error codes into apropriate actions in Prolog. Below is a typical example mapping the
statfs()
function:*/