/********************************************************
* File: file.c
* Created at Sun Jan 28 22:10:26 MSK 2001 by raorn // raorn@binec.ru
* Miscellaneous suff
* $Id: file.c,v 1.5 2001/11/10 19:22:56 raorn Exp $
*******************************************************/
#include <machine/defs.h>
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#ifdef HAVE_ERRNO_H
# include <errno.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include "file.h"
#include "mystrncpy.h"
bool Exists(uchar * file)
{
struct stat st;
if (stat(file, &st) == 0)
return (TRUE);
return (FALSE);
}
bool Lock(uchar * basename, bool bylink, bool usepid)
{
uchar buf[200], buf2[200];
FILE *fp;
long pid;
int rc;
snprintf(buf, 200, "%s.bsy", basename);
if ((fp = fopen(buf, "rt"))) {
if (usepid) {
fscanf(fp, "%ld", &pid);
fclose(fp);
if (kill(pid, 0) && errno == ESRCH)
unlink(buf);
else
return FALSE;
} else {
fclose(fp);
return FALSE;
}
}
if (bylink) {
mystrncpy(buf2, basename, 190);
snprintf(buf2+strlen(buf2), 200 - strlen(buf2), ".%ld", (long) getpid());
if (!(fp = fopen(buf2, "wt")))
return FALSE;
if (usepid)
fprintf(fp, "%10ld\n", (long) getpid());
fclose(fp);
#ifdef __MINGW32__
rc = rename(buf2, buf);
#else
rc = link(buf2, buf);
unlink(buf2);
#endif
if (rc)
return FALSE;
} else {
if ((rc = open(buf, O_WRONLY|O_CREAT|O_EXCL, 0644)) < 0)
return FALSE;
if (usepid) {
snprintf(buf2, 200, "%10ld\n", (long)getpid());
write(rc, buf2, strlen(buf2));
}
close(rc);
}
return TRUE;
}
void Unlock(uchar * basename)
{
uchar buf[200];
snprintf(buf, 200, "%s.bsy", basename);
unlink(buf);
}
syntax highlighted by Code2HTML, v. 0.9.1