+/*
+ * detach - detach us from the controlling terminal.
+ */
+void
+detach()
+{
+ int pid;
+
+ if (detached)
+ return;
+ if ((pid = fork()) < 0) {
+ error("Couldn't detach (fork failed: %m)");
+ die(1); /* or just return? */
+ }
+ if (pid != 0) {
+ /* parent */
+ if (locked)
+ relock(pid);
+ exit(0); /* parent dies */
+ }
+ setsid();
+ chdir("/");
+ close(0);
+ close(1);
+ close(2);
+ detached = 1;
+ log_to_fd = -1;
+ /* update pid files if they have been written already */
+ if (pidfilename[0])
+ create_pidfile();
+ if (linkpidfile[0])
+ create_linkpidfile();
+}
+
+/*
+ * reopen_log - (re)open our connection to syslog.
+ */
+void
+reopen_log()
+{
+#ifdef ULTRIX
+ openlog("pppd", LOG_PID);
+#else
+ openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
+ setlogmask(LOG_UPTO(LOG_INFO));
+#endif
+}
+
+/*
+ * Create a file containing our process ID.
+ */
+static void
+create_pidfile()
+{
+ FILE *pidfile;
+ char numbuf[16];
+
+ slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
+ _PATH_VARRUN, ifname);
+ if ((pidfile = fopen(pidfilename, "w")) != NULL) {
+ fprintf(pidfile, "%d\n", getpid());
+ (void) fclose(pidfile);
+ } else {
+ error("Failed to create pid file %s: %m", pidfilename);
+ pidfilename[0] = 0;
+ }
+ slprintf(numbuf, sizeof(numbuf), "%d", getpid());
+ script_setenv("PPPD_PID", numbuf);
+ if (linkpidfile[0])
+ create_linkpidfile();
+}
+
+static void
+create_linkpidfile()
+{
+ FILE *pidfile;
+
+ if (linkname[0] == 0)
+ return;
+ slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
+ _PATH_VARRUN, linkname);
+ if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
+ fprintf(pidfile, "%d\n", getpid());
+ if (pidfilename[0])
+ fprintf(pidfile, "%s\n", ifname);
+ (void) fclose(pidfile);
+ } else {
+ error("Failed to create pid file %s: %m", linkpidfile);
+ linkpidfile[0] = 0;
+ }
+ script_setenv("LINKNAME", linkname);
+}
+