/******************************************************** * 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 #ifdef HAVE_SYS_STAT_H # include #endif #include #include #include #include #ifdef HAVE_ERRNO_H # include #endif #ifdef HAVE_FCNTL_H #include #endif #ifdef HAVE_UNISTD_H # include #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); }