log_open函数的作用是打开一个记录文件,其作用与fopen函数类似.
log_t *log_open( char *fname, int flags )
{
log_t *log = malloc(sizeof(log_t));
if(!log)
{
fprintf(stderr, "log_open: Unable to malloc()");
goto log_open_a;
}
log->flags=flags;
if( !strcmp(fname,"-") )
{
log->fd = 2;
}
else
{
log->fd = open(fname, O_WRONLY|O_CREAT|O_NOCTTY |
(flags&LOG_TRUNC ? O_TRUNC : O_APPEND) , 0666);
}
if( log->fd == -1 )
{
fprintf(stderr, "log_open: Opening logfile %s: %s", fname, strerror(errno));
goto log_open_b;
}
if( sem_init(&log->sem, 0, 1) == -1 )
{
fprintf(stderr, "log_open: Could not initialize log semaphore.");
goto log_open_c;
}
return log;
log_open_c:
close(log->fd);
log_open_b:
free(log);
log_open_a:
return NULL;
}
log_close函数的作用是关闭一个打开的记录文件.通常在函数退出的时候执行这个函数,以保证所有记录信息都正确的写入记录文件.
void log_close( log_t *log )
{
sem_wait(&log->sem);
sem_destroy(&log->sem);
close(log->fd);
free(log);
return;
}