
/* cift13-c.c -- CIF test 13, C part */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>

#include "cifccsp.h"

void my_bsyscall (char *string)
{
	struct timeval tv = {2, 0};

	fprintf (stderr, "the message was [%s]\n", string);
	select (0, NULL, NULL, NULL, &tv);
	fprintf (stderr, "the message was [%s]\n", string);

	return;
}
	

void out_string (char *str, Channel *out)
{
	unsigned char *ch = (unsigned char *)str;

	while (*ch != '\0') {
		/* ChanOut (out, ch, 1); */
		ChanOutChar (out, *ch);
		ch++;
	}
	return;
}

void proc_p1 (Process *me, Channel *kroc_err, Channel *killchan)
{
	BLOCKING_KILLCALLN (my_bsyscall, killchan, "wibble!");
	out_string ("that should have worked!\n", kroc_err);
	return;
}

void proc_p2 (Process *me, Channel *killchan)
{
	int result;

	EXTERNAL_CALLN (fprintf, stderr, "proc_p2: sleeping for 200000 and killing process.\n");
	ProcAfter (200000);
	BLOCKING_CALL_KILL (killchan, &result);
	EXTERNAL_CALLN (fprintf, stderr, "proc_p2: killed process, got result = %d.\n", result);

	return;
}

void my_process (Process *me, Channel *kroc_err)
{
	Channel killchan;
	Process *p1 = ProcAlloc (proc_p1, 4096, 2, kroc_err, &killchan);
	Process *p2 = ProcAlloc (proc_p2, 4096, 1, &killchan);

	ChanInit (&killchan);
	ProcPar (p1, p2, NULL);

	ProcAllocClean (p1);
	ProcAllocClean (p2);

	return;
}

/* allocates process and returns address to occam world */
void real_cift13_init (int *raddr, Channel *c)
{
	Process *p = ProcAlloc (my_process, 4096, 1, c);

	*raddr = (int)p;
	return;
}

/* frees memory used by a process -- lets hope it's finished :) */
void real_cift13_free (int addr)
{
	Process *p = (Process *)addr;

	ProcAllocClean (p);
	return;
}

void _cift13_init (int *ws) { real_cift13_init ((int *)(ws[0]), (Channel *)(ws[1])); }
void _cift13_free (int *ws) { real_cift13_free ((int)(ws[0])); }

