if (flock(fd, LOCK_EX|LOCK_NB) < OK) { int save_errno = errno;  if (fscanf(fp, "%d", &otherpid) == 1) snprintf(buf, sizeof buf, "can't lock %s, otherpid may be %d: %s", pidfile, otherpid, strerror(save_errno)); else snprintf(buf, sizeof buf, "can't lock %s, otherpid unknown: %s", pidfile, strerror(save_errno)); fprintf(stderr, "%s: %s\n", ProgramName, buf); log_it("CRON", getpid(), "DEATH", buf); exit(ERROR_EXIT); }
acquire_daemonlock(closeflag)	int closeflag;{	static	FILE	*fp = NULL;	char		buf[3*MAX_FNAME];	char		pidfile[MAX_FNAME];	int		fd;	PID_T		otherpid;	if (closeflag && fp) {		fclose(fp);		fp = NULL;		return;	}	if (!fp) {		if (!glue_strings(pidfile, sizeof pidfile, PIDDIR,		    PIDFILE, '/')) {			fprintf(stderr, "%s/%s: path too long\n",				PIDDIR, PIDFILE);			log_it("CRON", getpid(), "DEATH", "path too long");			exit(ERROR_EXIT);		}		if ((-1 == (fd = open(pidfile, O_RDWR|O_CREAT, 0644))) ||		    (NULL == (fp = fdopen(fd, "r+")))) {			snprintf(buf, sizeof buf, "can't open or create %s: %s",				pidfile, strerror(errno));			fprintf(stderr, "%s: %s\n", ProgramName, buf);			log_it("CRON", getpid(), "DEATH", buf);			exit(ERROR_EXIT);		}		if (flock(fd, LOCK_EX|LOCK_NB) < OK) {			int save_errno = errno;			if (fscanf(fp, "%d", &otherpid) == 1)				snprintf(buf, sizeof buf,				    "can't lock %s, otherpid may be %d: %s",				    pidfile, otherpid, strerror(save_errno));			else				snprintf(buf, sizeof buf,				    "can't lock %s, otherpid unknown: %s",				    pidfile, strerror(save_errno));			fprintf(stderr, "%s: %s\n", ProgramName, buf);			log_it("CRON", getpid(), "DEATH", buf);			exit(ERROR_EXIT);		}		(void) fcntl(fd, F_SETFD, 1);	}	rewind(fp);	fprintf(fp, "%ld\n", (long)getpid());	fflush(fp);	(void) ftruncate(fileno(fp), ftell(fp));	/* abandon fd and fp even though the file is open. we need to	 * keep it open and locked, but we don't need the handles elsewhere.	 */}