Subject: [SWIPL] Thread Create using Sockets

From: "Douglas R. Miles" <[email-masked]>
Date: Thu, 2 Aug 2001 09:17:02 -0700

I am having trouble with the program bellow:

It creates the thread properly.. But the input stream '$stream'(...) sent to
the child thread does not seem to be available to it .  Are streams global?
If so then I should not be having a problem.. If they are not, how can I
pass the input output streams to the child (the ones in from
tcp_open_socket/3)?

:- use_module(library(socket)).  
:- use_module(library(threadutil)).         

swi_server :-
        write_ln(swi_server('Port':5001)),
        tcp_socket(Socket),
        tcp_bind(Socket, 5001),
        tcp_listen(Socket, 5),
        tcp_open_socket(Socket, AcceptFd, _),
        do_accept(AcceptFd).

do_accept(AcceptFd) :-   
         sleep(0.1),
         tcp_accept(AcceptFd, Socket, _PeerIP),
         writeq(_PeerIP),nl,
	   thread_create(
		 handle_the_socket(Socket,In, Out),
	    Id,[detatched(true)]),
	 !,
	  do_accept(AcceptFd).

handle_the_socket(Socket,In, Out):-
	 tcp_open_socket(Socket, In, Out),
         writeq( (in=In, out=Out) ), nl,flush_output,
 
catch(service_telnet_request(In,Out),E,writeq(service_one_client(E))),
	          flush_output(Out),
		 ignore((
		    catch(close(In),_,true),
		    catch(close(Out),_,true),
		    catch(tcp_close_socket(Socket),_,true)
		    )).

service_telnet_request(In,Out):-
         once((
catch(read_term(In,CMD,[variable_names(Vars)]),_,(write_ln(Out,'<BadInput/>'
),flush_output(Out))))),
	   tell(Out),
	   catch(invoke_cmd(Out,CMD,Vars,Start),_,true),
         catch(flush_output(Out),_,true).

invoke_cmd(Out,CMD,Vars,_):-
	call(CMD),write_swi_vars_proc(Out,Vars),fail.
invoke_cmd(Out,CMD,Vars,_):-!.

write_swi_vars_proc(Out,[]):-!.
write_swi_vars_proc(Out,Vars):-
            write(Out,'<P>'),
            write_swi_vars(Out,Vars),
            format(Out,'<hr>~n',[]).
                              
write_swi_vars(Out,[]):-!.
write_swi_vars(Out,[Term|REST]):-  !,Term=..[_,N,V],
         format(Out,'<A>~w = ~q</A><br>',[N,V]),
         write_swi_vars(Out,REST).

Thank you in Advance,

Douglas