# Write a pid file before forking
# Patch origin: Wind River

Index: nfs-server-2.2beta47/daemon.c
===================================================================
--- nfs-server-2.2beta47.orig/daemon.c
+++ nfs-server-2.2beta47/daemon.c
@@ -15,6 +15,19 @@
 static const char *	pidfilename = 0;
 static const char *	get_signame(int signo);
 
+void
+writepid(pid_t pid, int clear)
+{
+	FILE	*fp;
+
+	fp = fopen(pidfilename, clear? "w" : "a");
+	if (fp == NULL)
+		Dprintf(L_FATAL, "Unable to open %s: %m", pidfilename);
+	fprintf(fp, "%d\n", pid);
+	fclose(fp);
+	return;
+}
+
 /*
  * Do the Crawley Thing
  */
@@ -33,8 +46,10 @@ daemonize(void)
 		Dprintf(L_FATAL, "unable to fork: %s", strerror(errno));
 
 	/* Parent process: exit */
-	if (c > 0)
+	if (c > 0) {
+		writepid(c, 1);
 		exit(0);
+	}
 
 	/* Do the session stuff */
 	close(0);
@@ -60,19 +75,6 @@ setpidpath(const char *filename)
 }
 
 void
-writepid(pid_t pid, int clear)
-{
-	FILE	*fp;
-
-	fp = fopen(pidfilename, clear? "w" : "a");
-	if (fp == NULL)
-		Dprintf(L_FATAL, "Unable to open %s: %m", pidfilename);
-	fprintf(fp, "%d\n", pid);
-	fclose(fp);
-	return;
-}
-
-void
 failsafe(int level, int ncopies)
 {
 	int	*servers, running, child, i;
Index: nfs-server-2.2beta47/mountd.c
===================================================================
--- nfs-server-2.2beta47.orig/mountd.c
+++ nfs-server-2.2beta47/mountd.c
@@ -425,9 +425,6 @@ main(int argc, char **argv)
 		background_logging();
 	}
 
-	/* Become a daemon */
-	if (!foreground)
-		daemonize();
 
 	/* Initialize the FH module. */
 	fh_init();
@@ -435,11 +432,15 @@ main(int argc, char **argv)
 	/* Initialize the AUTH module. */
 	auth_init(auth_file);
 
-	/* Write pidfile */
     if (mount_pid_file == 0)
         mount_pid_file = _PATH_MOUNTD_PIDFILE;
     setpidpath(mount_pid_file);
-	writepid(getpid(), 1);
+
+	/* Become a daemon */
+	if (!foreground)
+		daemonize();
+	else
+		writepid(getpid(), 1);
 
 	/* Failsafe mode */
 	if (failsafe_level)
Index: nfs-server-2.2beta47/nfsd.c
===================================================================
--- nfs-server-2.2beta47.orig/nfsd.c
+++ nfs-server-2.2beta47/nfsd.c
@@ -1147,11 +1147,6 @@ main(int argc, char **argv)
 	/* if (ncopies > 1)
 		read_only = 1; */
 
-	/*
-	 * We first fork off a child and detach from tty
-	 */
-	if (!foreground)
-		daemonize();
 
 	/* Initialize the AUTH module. */
 	auth_init(auth_file);
@@ -1160,9 +1155,16 @@ main(int argc, char **argv)
         nfs_pid_file = _PATH_NFSD_PIDFILE;
     setpidpath(nfs_pid_file);
 
+	/*
+	 * We first fork off a child and detach from tty
+	 */
+	if (!foreground)
+		daemonize();
+	else
+		writepid(getpid(), 1);
+
 	if (failsafe_level == 0) {
 		/* Start multiple copies of the server */
-		writepid(getpid(), 1);
 		for (i = 1; i < ncopies; i++) {
 			pid_t	pid;
 
