out_file.c
author viric@llimona
Tue, 30 May 2006 12:02:13 +0200
changeset 55 c72dbd390cf2
parent 53 667cd5966695
permissions -rw-r--r--
Now the tcp_server sends the log file. The tcp server is now shutted down by its own function call.

#include <sys/types.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <assert.h>
#include <fcntl.h>

#include "syslog.h"

/* Prototypes */
static int init_handle(const char * restrict name);

/* Local globals */
static int out_file;
static bool file_enabled = false;


/* Returns -2 when the file wasn't initialized by config, 0 when all was ok,
 * -1 on more important error */
int init_out_file()
{
	char name[MAX_STRING];

	assert (get_config(LOG_FILE, name, MAX_STRING) > 0);

	if (strncmp(name, "disabled", MAX_STRING) == 0)
		return -2;

	return init_handle(name);
}

/* Returns 0 when all was ok, -1 on error */
static int init_handle(const char * restrict name)
{
	/* We must specify the mode, because we add O_CREAD */
	out_file = open(name, O_WRONLY | O_APPEND | O_CREAT, 0600);
	if (out_file == -1)
	{
		fprintf(stderr, "Error opening the log file: %s\n",
				strerror(errno));
		return -1;
	}

	file_enabled = true;

	return 0;
}


/* Return -2 when the file is not enabled. Otherwise, the output of send().*/
int write_out_file(const char * restrict buf, const int len)
{
	int res, res2;

	if (!file_enabled)
		return -2;

	res = write(out_file, buf, len);
	res2 = write(out_file, "\n", 1);
	if (res == -1 || res2 == -1)
	{
		fprintf(stderr, "Error writing to the log file: %s\n", 
			strerror(errno));
	} 

	return res;
}

/* Return -2 when the file is not enabled. Otherwise, the output of close().*/
int close_out_file()
{
	int res;

	if (!file_enabled)
		return -2;

	res = close(out_file);

	if (res == -1)
	{
		fprintf(stderr, "Error closing the log file: %s\n", 
			strerror(errno));
	}
	file_enabled = false;

	return res;
	
}