[sheepdog] [PATCH] sheep: let sheep return correct exit status when locking a base directory fails

Hitoshi Mitake mitake.hitoshi at gmail.com
Mon May 6 18:15:41 CEST 2013


Currently, lock_and_daemon() always returns 0 as its exit
status. But this behavior is confusing because users cannot detect
errors during locking a base directory via the exit status. This patch
modifies lock_and_daemon() for returning correct exit status.

Signed-off-by: Hitoshi Mitake <mitake.hitoshi at lab.ntt.co.jp>
---
 sheep/sheep.c |   49 +++++++++++++++++++++++++++++++++++++------------
 1 files changed, 37 insertions(+), 12 deletions(-)

diff --git a/sheep/sheep.c b/sheep/sheep.c
index a7e3820..64f04ca 100644
--- a/sheep/sheep.c
+++ b/sheep/sheep.c
@@ -392,7 +392,12 @@ static void check_host_env(void)
 
 static int lock_and_daemon(bool daemonize, const char *base_dir)
 {
-	int ret, devnull_fd = 0;
+	int ret, devnull_fd = 0, status = 0;
+	int pipefd[2];
+
+	ret = pipe(pipefd);
+	if (ret < 0)
+		panic("pipe() for passing exit status failed: %m");
 
 	if (daemonize) {
 		switch (fork()) {
@@ -402,36 +407,51 @@ static int lock_and_daemon(bool daemonize, const char *base_dir)
 			panic("fork() failed during daemonize: %m");
 			break;
 		default:
-			exit(0);
+			ret = read(pipefd[0], &status, sizeof(status));
+			if (ret != sizeof(status))
+				panic("read exit status failed: %m");
+
+			exit(status);
 			break;
 		}
 
-		if (setsid() == -1)
-			panic("becoming a leader of a new session failed: %m");
+		if (setsid() == -1) {
+			sd_eprintf("becoming a leader of a new session"
+				" failed: %m");
+			status = 1;
+			goto end;
+		}
 
 		switch (fork()) {
 		case 0:
 			break;
 		case -1:
-			panic("fork() failed during daemonize: %m");
-			break;
+			sd_eprintf("fork() failed during daemonize: %m");
+			goto end;
 		default:
 			exit(0);
 			break;
 		}
 
-		if (chdir("/"))
-			panic("chdir to / failed: %m");
+		if (chdir("/")) {
+			sd_eprintf("chdir to / failed: %m");
+			status = 1;
+			goto end;
+		}
 
 		devnull_fd = open("/dev/null", O_RDWR);
-		if (devnull_fd < 0)
-			panic("opening /dev/null failed: %m");
+		if (devnull_fd < 0) {
+			sd_eprintf("opening /dev/null failed: %m");
+			status = 1;
+			goto end;
+		}
 	}
 
 	ret = lock_base_dir(base_dir);
 	if (ret < 0) {
 		sd_eprintf("locking directory: %s failed", base_dir);
-		return -1;
+		status = 1;
+		goto end;
 	}
 
 	if (daemonize) {
@@ -446,7 +466,12 @@ static int lock_and_daemon(bool daemonize, const char *base_dir)
 		close(devnull_fd);
 	}
 
-	return 0;
+end:
+	ret = write(pipefd[1], &status, sizeof(status));
+	if (ret != sizeof(status))
+		panic("writing exit status failed: %m");
+
+	return status;
 }
 
 int main(int argc, char **argv)
-- 
1.7.5.1




More information about the sheepdog mailing list