utils: fix lxc_p{close,open}()

If a file descriptor fd is opened by fdopen() and associated with a stream f will **not** have been dup()ed. This means that fclose(f) will also close the fd. So never call close(fd) after fdopen(fd) succeeded. This fixes a double close() Stéphane and I observed when debugging on aarch64 and armf. Signed-off-by: 's avatarChristian Brauner <christian.brauner@ubuntu.com>
parent e99cf4ac
...@@ -509,10 +509,14 @@ struct lxc_popen_FILE *lxc_popen(const char *command) ...@@ -509,10 +509,14 @@ struct lxc_popen_FILE *lxc_popen(const char *command)
fp = malloc(sizeof(*fp)); fp = malloc(sizeof(*fp));
if (!fp) if (!fp)
goto on_error; goto on_error;
memset(fp, 0, sizeof(*fp));
fp->child_pid = child_pid; fp->child_pid = child_pid;
fp->pipe = pipe_fds[0]; fp->pipe = pipe_fds[0];
/* From now on, closing fp->f will also close fp->pipe. So only ever
* call fclose(fp->f).
*/
fp->f = fdopen(pipe_fds[0], "r"); fp->f = fdopen(pipe_fds[0], "r");
if (!fp->f) if (!fp->f)
goto on_error; goto on_error;
...@@ -520,15 +524,22 @@ struct lxc_popen_FILE *lxc_popen(const char *command) ...@@ -520,15 +524,22 @@ struct lxc_popen_FILE *lxc_popen(const char *command)
return fp; return fp;
on_error: on_error:
if (fp) /* We can only close pipe_fds[0] if fdopen() didn't succeed or wasn't
free(fp); * called yet. Otherwise the fd belongs to the file opened by fdopen()
* since it isn't dup()ed.
if (pipe_fds[0] >= 0) */
if (fp && !fp->f && pipe_fds[0] >= 0)
close(pipe_fds[0]); close(pipe_fds[0]);
if (pipe_fds[1] >= 0) if (pipe_fds[1] >= 0)
close(pipe_fds[1]); close(pipe_fds[1]);
if (fp && fp->f)
fclose(fp->f);
if (fp)
free(fp);
return NULL; return NULL;
} }
...@@ -544,7 +555,6 @@ int lxc_pclose(struct lxc_popen_FILE *fp) ...@@ -544,7 +555,6 @@ int lxc_pclose(struct lxc_popen_FILE *fp)
wait_pid = waitpid(fp->child_pid, &wstatus, 0); wait_pid = waitpid(fp->child_pid, &wstatus, 0);
} while (wait_pid < 0 && errno == EINTR); } while (wait_pid < 0 && errno == EINTR);
close(fp->pipe);
fclose(fp->f); fclose(fp->f);
free(fp); free(fp);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment