+ int lockfd = acquire_lock();
+ fd = connect_existing();
+ if (fd >= 0) { close(lockfd); return fd; }
+
+ // We must start a fresh one, and we hold the lock
+
+ r = unlink(socketpath);
+ if (r<0) diee("failed to remove stale socket %s", socketpath);
+
+ int fake_pair[2];
+ r = socketpair(AF_UNIX, SOCK_STREAM, 0, fake_pair);
+ if (r<0) diee("socketpair() for fake initial connection");
+
+ int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
+ if (sfd<0) diee("socket() for new listener");
+
+ salen_t salen = sizeof(sun);
+ r= bind(sfd, (const struct sockaddr*)&socket_sun, saledn);
+ if (r<0) diee("bind() on new listener");
+
+ // We never want callers to get ECONNREFUSED!.
+ // There is a race here: from my RTFM they may get ECONNREFUSED
+ // if they tr between our bind() and listen(). But if they do, they'll
+ // acquire the lock (serialising with us) and retry, and then it will work.
+ r = listen(sfd, INT_MAX);
+ if (r<0) diee("listen() for new listener");
+
+ pid_t setup_pid = fork();
+ if (setup_pid == (pid_t)-1) diee("fork for spawn setup");
+ if (!setup_pid) become_setup(sfd, fake_pair);
+ close(fake_pair[1]);
+ close(sfd);
+
+ int status;
+ pid_t got = waitpid(setup_pid, &status, 0);
+ if (got == (pid_t)-1) diee("waitpid setup [%ld]", (long)setup_pid);
+ if (got != setup_pid) diee("waitpid setup [%ld] gave [%ld]!",
+ (long)setup_pid, (long)got);
+ if (status != 0) propagate_exit_status(status);
+
+ close(lockfd);
+ return fake_pair[0];
+}