Skip to content

Commit

Permalink
Close stdin/stdout file descriptors properly
Browse files Browse the repository at this point in the history
wl-copy shouldn't hold up a pipeline by forking with the stdout file
descriptor left open. Replacing stdin/stdout with /dev/null should
also handle errors when opening /dev/null.

Closes #100
  • Loading branch information
Seirdy committed Nov 6, 2020
1 parent 2c3cee1 commit aa4633b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/util/files.c
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,13 @@ char *infer_mime_type_from_contents(const char *file_path) {
close(pipefd[0]);
close(pipefd[1]);
int devnull = open("/dev/null", O_RDONLY);
dup2(devnull, STDIN_FILENO);
close(devnull);
if (devnull >= 0) {
dup2(devnull, STDIN_FILENO);
close(devnull);
} else {
/* If we cannot open /dev/null, just close stdin */
close(STDIN_FILENO);
}
execlp("xdg-mime", "xdg-mime", "query", "filetype", file_path, NULL);
exit(1);
}
Expand Down
14 changes: 14 additions & 0 deletions src/wl-copy.c
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
#include <wayland-client.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h> // open
#include <libgen.h>
#include <getopt.h>

Expand All @@ -53,7 +54,20 @@ static void did_set_selection_callback(struct copy_action *copy_action) {
* We fork our process and leave the
* child running in the background,
* while exiting in the parent.
* Also replace stdin/stdout with
* /dev/null so the stdout file
* descriptor isn't kept alive.
*/
int devnull = open("/dev/null", O_RDWR);
if (devnull >= 0) {
dup2(devnull, STDOUT_FILENO);
dup2(devnull, STDIN_FILENO);
close(devnull);
} else {
/* If we cannot open /dev/null, just close stdin/stdout */
close(STDIN_FILENO);
close(STDOUT_FILENO);
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
Expand Down

0 comments on commit aa4633b

Please sign in to comment.