//
// 
//	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
// 
//	This program is free software; you can redistribute it 
//	and/or modify it under the terms of the GLOBALBASE 
//	Library General Public License (G-LGPL) as published by 
//
//	http://www.globalbase.org/
// 
//	This program is distributed in the hope that it will be 
//	useful, but WITHOUT ANY WARRANTY; without even the 
//	implied warranty of MERCHANTABILITY or FITNESS FOR A 
//	PARTICULAR PURPOSE.
//
//

extern "C" {

#define STREAM_LIB

#include	<signal.h>
#include	<errno.h>
#include	"task.h"
#include	"pri_level.h"
#include	"stream.h"
#include	"lock_level.h"
#include	"LTCPEndpoint.h"

extern SEM stream_lock;


STREAM * close_stream;

void close_sync_task();
int get_tid();
void init_file_stream();
void init_socket_stream();
void init_terminal_stream();
void init_flush_pipe_stream();


void
init_machine_stream()
{
	create_task(close_sync_task,0,PRI_TICK_CLOSE);

	init_file_stream();
	init_socket_stream();
	init_terminal_stream();
	init_flush_pipe_stream();
}

void
close_sync_task()
{
	for ( ; ; ) {
		sleep_sec(2);
		lock_task(stream_lock);
		if ( close_stream )
			wakeup_task((int)&close_stream->h.thread);
		unlock_task(stream_lock,"close_sync_func");
	}
}


void
_s_close_sync(STREAM * s)
{
	for ( ; close_stream ; ) {
		sleep_task((int)&close_stream,stream_lock);
		lock_task(stream_lock);
	}
	close_stream = s;

	for ( ; ; ) {
		if ( s->h.thread == 0 )
			break;
		s->socket.ep->AbortThreadOperation((LThread*)s->h.thread->tid);
		sleep_task((int)&s->h.thread,stream_lock);
		lock_task(stream_lock);
	}
	close_stream = 0;
	wakeup_task((int)&close_stream);
}

} // extern "C"