Avoid left over dot lock file after reboot

---
 dotlock.c |   20 +++++++++++---------
 dotlock.h |    2 +-
 sh.hist.c |   11 +++++++----
 3 files changed, 19 insertions(+), 14 deletions(-)

--- dotlock.c
+++ dotlock.c	2020-02-19 10:00:31.999490600 +0000
@@ -76,7 +76,7 @@ create_exclusive(const char *fname)
 	 * We try to create the unique filename.
 	 */
 	for (ntries = 0; ntries < 5; ntries++) {
-		fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL|O_SYNC, 0);
+		fd = open(path, O_WRONLY|O_CREAT|O_TRUNC|O_EXCL|O_SYNC, S_IWUSR);
 		if (fd != -1) {
 			(void)close(fd);
 			break;
@@ -110,8 +110,14 @@ create_exclusive(const char *fname)
 		errno = EEXIST;
 		return -1;
 	}
-	return 0;
 
+	fd = open(fname, O_WRONLY|O_EXCL|O_SYNC, 0);
+	if (fd < 0) {
+		errno = EEXIST;
+		return -1;
+	}
+	(void)unlink(fname);
+	return fd;
 bad:
 	serrno = errno;
 	(void)unlink(path);
@@ -146,9 +152,8 @@ dot_lock(const char *fname, int pollinte
 	for (;;) {
 		handle_pending_signals();
 		(void)sigprocmask(SIG_BLOCK, &nset, &oset);
-		if (create_exclusive(path) != -1) {
+		if ((retval = create_exclusive(path)) != -1) {
 			(void)sigprocmask(SIG_SETMASK, &oset, NULL);
-			retval = 0;
 			break;
 		}
 		else
@@ -170,10 +175,7 @@ dot_lock(const char *fname, int pollinte
 }
 
 void
-dot_unlock(const char *fname)
+dot_unlock(const int fd)
 {
-	char path[MAXPATHLEN];
-
-	(void)snprintf(path, sizeof(path), "%s.lock", fname);
-	(void)unlink(path);
+	close(fd);
 }
--- dotlock.h
+++ dotlock.h	2020-02-19 09:40:16.034422159 +0000
@@ -30,6 +30,6 @@
  * pollinterval -- Interval (miliseconds) to check for lock, -1 return
  */
 int dot_lock(const char *fname, int pollinterval);
-void dot_unlock(const char *fname);
+void dot_unlock(const int fd);
 
 #endif /* #ifndef _DOTLOCK_H_ */
--- sh.hist.c
+++ sh.hist.c	2020-02-19 09:48:57.640589111 +0000
@@ -1209,9 +1209,11 @@ fmthist(int fmt, ptr_t ptr)
 }
 
 static void
-dotlock_cleanup(void* lockpath)
+dotlock_cleanup(void* xfdp)
 {
-	dot_unlock((char*)lockpath);
+	int *fdp;
+	fdp = xfdp;
+	dot_unlock(*fdp);
 }
 
 /* Save history before exiting the shell. */
@@ -1284,11 +1286,12 @@ rechist(Char *fname, int ref)
 	    jmp_buf_t osetexit;
 	    if (lock) {
 #ifndef WINNT_NATIVE
+		int fdlk;
 		char *lockpath = strsave(short2str(fname));
 		cleanup_push(lockpath, xfree);
 		/* Poll in 100 miliseconds interval to obtain the lock. */
-		if ((dot_lock(lockpath, 100) == 0))
-		    cleanup_push(lockpath, dotlock_cleanup);
+		if ((fdlk = dot_lock(lockpath, 100)) != -1)
+		    cleanup_push(&fdlk, dotlock_cleanup);
 #endif
 	    }
 	    getexit(osetexit);
