[mercury-users] Examples of posix module
Fergus Henderson
fjh at cs.mu.OZ.AU
Sun Apr 29 23:15:16 AEST 2001
On 28-Apr-2001, John Eikenberry <jae at zhar.net> wrote:
>
> Are there any examples of the posix extras module available (besides
> hello.m that comes with it)?
Not that I know of.
> My goal is to figure out how to use posix select to monitor stdin/stdout.
> And while I'd like to figure this out myself from examples and docs, if its
> easier to just show me how to do it I'd appreciate a basic example. I have
> use select before, but only in python. I also have some prolog experience,
> but it was a few years ago and never with select.
I've attached a simple example, which I took from the Linux man page for
select() and converted to Mercury, with some minor adaptions.
This just reads from stdin with a timeout.
The Posix interface is a fairly thin binding, so the interface is
quite similar to the equivalent in C. A few of the details differ,
but those should hopefully be clear from the Mercury type and mode
declarations.
--
Fergus Henderson <fjh at cs.mu.oz.au> | "I have always known that the pursuit
| of excellence is a lethal habit"
WWW: <http://www.cs.mu.oz.au/~fjh> | -- the last words of T. S. Garp.
-------------- next part --------------
% This module shows an example of the use of `select'.
:- module select_example.
:- interface.
:- import_module io.
:- pred main(io__state, io__state).
:- mode main(di, uo) is det.
:- implementation.
:- import_module int, exception, posix, posix__select.
main -->
new_fdset_ptr(ReadFDSet),
new_fdset_ptr(WriteFDSet),
new_fdset_ptr(ExceptFDSet),
{ StdinFD = 0 },
fd_set(fd(StdinFD), ReadFDSet),
{ TimeToWait = timeval(5 /* seconds, + */, 0 /* microseconds */) },
{ MaxFD = StdinFD },
posix__select__select(MaxFD + 1, ReadFDSet, WriteFDSet, ExceptFDSet,
TimeToWait, Result),
(
{ Result = ok(NumFDs) },
(if { NumFDs > 0 } then
print("Data is available now.\n"),
/* fd_isset(StdinFD, ReadFDSet, X) will give X=yes. */
io__read_line_as_string(StringRes),
(if { StringRes = ok(String) } then
print("Data read: "), print(String), nl
else
{ throw("wierd, something went wrong") }
)
else
print("No data within five seconds.\n")
)
;
{ Result = error(Errno) },
print("Error: "), print(Errno), nl
).
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: example.c
URL: <http://lists.mercurylang.org/archives/users/attachments/20010429/7fb1bd18/attachment.c>
More information about the users
mailing list