veyron/runtimes/google/rt: Port the agent fd duping logic to veyron2.Init().

Change-Id: If63d884d6ddd4811f0c92857c9b62b14e16e10e7
diff --git a/runtimes/google/rt/securityx.go b/runtimes/google/rt/securityx.go
index 040ca83..ab640df 100644
--- a/runtimes/google/rt/securityx.go
+++ b/runtimes/google/rt/securityx.go
@@ -40,7 +40,7 @@
 	if fd, err := agentFD(handle); err != nil {
 		return nil, err
 	} else if fd >= 0 {
-		return agent.NewAgentPrincipal(ctx, fd, client)
+		return connectToAgent(ctx, fd, client)
 	}
 	if len(credentials) > 0 {
 		// TODO(ataly, ashankar): If multiple runtimes are getting
@@ -97,3 +97,17 @@
 	}
 	return fmt.Sprintf("%s-%d", name, os.Getpid())
 }
+
+func connectToAgent(ctx *context.T, fd int, client ipc.Client) (security.Principal, error) {
+	// Dup the fd, so we can create multiple runtimes.
+	syscall.ForkLock.Lock()
+	newfd, err := syscall.Dup(fd)
+	if err == nil {
+		syscall.CloseOnExec(newfd)
+	}
+	syscall.ForkLock.Unlock()
+	if err != nil {
+		return nil, err
+	}
+	return agent.NewAgentPrincipal(ctx, newfd, client)
+}