From: Brian Norris <banorris@uci.edu>
Date: Thu, 4 Apr 2013 19:55:33 +0000 (-0700)
Subject: common: improve redirect_output() error handling
X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=964ae5c3c62fc383c53e90b20f32ba17b7b616ab;p=cdsspec-compiler.git

common: improve redirect_output() error handling

Check the return code and errno results of all system/library calls.
Also delete the extraneous 'fd' variable and use the appropriate
STDOUT_FILENO macro instead of fileno(stdout).
---

diff --git a/common.cc b/common.cc
index a43064d..338058d 100644
--- a/common.cc
+++ b/common.cc
@@ -88,10 +88,12 @@ static int fd_user_out; /**< @brief File descriptor from which to read user prog
  */
 void redirect_output()
 {
-	int fd;
-
 	/* Save stdout for later use */
-	model_out = dup(fileno(stdout));
+	model_out = dup(STDOUT_FILENO);
+	if (model_out < 0) {
+		perror("dup");
+		exit(EXIT_FAILURE);
+	}
 
 	/* Redirect program output to a pipe */
 	int pipefd[2];
@@ -99,11 +101,17 @@ void redirect_output()
 		perror("pipe");
 		exit(EXIT_FAILURE);
 	}
-	fd = dup2(pipefd[1], fileno(stdout)); // STDOUT_FILENO
+	if (dup2(pipefd[1], STDOUT_FILENO) < 0) {
+		perror("dup2");
+		exit(EXIT_FAILURE);
+	}
 	close(pipefd[1]);
 
 	/* Save the "read" side of the pipe for use later */
-	fcntl(pipefd[0], F_SETFL, O_NONBLOCK);
+	if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) < 0) {
+		perror("fcntl");
+		exit(EXIT_FAILURE);
+	}
 	fd_user_out = pipefd[0];
 }