/*
 * Copyright (c) 2002, 2004, 2005 Sendmail, Inc. and its suppliers.
 *	All rights reserved.
 *
 * By using this file, you agree to the terms and conditions set
 * forth in the LICENSE file which can be found at the top level of
 * the sendmail distribution.
 */

#include "sm/generic.h"
SM_IDSTR(id, "@(#)$Id: t-stdio-2.c,v 1.9 2006/07/16 02:07:39 ca Exp $")
#include "sm/error.h"
#include "sm/io.h"
#include "sm/test.h"
#include <stdio.h>

#define SM_N_CHARS	1024

static void
prtline(sm_file_T *fp, char *l)
{
	size_t n;
	ssize_t r;
	sm_ret_T res;

	n = strlen(l);
	res = sm_io_write(fp, (uchar *) l, n, &r);
	SM_TEST(!sm_is_err(res));
	SM_TEST(n == (size_t) r);
}

static void
test(sm_file_T *fp)
{
	prtline(fp, "This is the first line\n");
	sleep(1);
	prtline(fp, "This is the second line ");
	sleep(1);
	prtline(fp, "and this is the continuation of the second line\n");
	sleep(1);
	prtline(fp, "This is the last line\n");
}

int
main(int argc, char *argv[])
{
	sm_ret_T res;
	sm_file_T *fp;

	sm_test_begin(argc, argv, "test sm_io_write buffering");

	/* this makes only sense if someone is watching... use -v? */
	if (!SmTestVerbose)
	{
		prtline(smioout,
			"Test I/O buffering: run with -v to observe it\n");
		prtline(smioout,
			"Notice: line buffering and unbuffered I/O has been turned off.\n");
		sm_io_flush(smioout);
		return sm_test_end();
	}
	prtline(smioout, "Test line buffered\n");
	test(smioout);
	sm_io_flush(smioout);
	prtline(smioout, "Test unbuffered\n");
	test(smioerr);
	sm_io_flush(smioerr);
	res = sm_io_open(SmStStdio, "/dev/tty", SM_IO_WRONLY, &fp, SM_IO_WHAT_END);
	SM_TEST(res == SM_SUCCESS);
	SM_TEST(fp != NULL);
	if (fp != NULL)
	{
		prtline(smioout, "Test buffered\n");
		test(fp);
		sm_io_flush(fp);
		res = sm_io_close(fp, SM_IO_CF_NONE);
		SM_TEST(res == SM_SUCCESS);
	}
	return sm_test_end();
}


syntax highlighted by Code2HTML, v. 0.9.1