Skip to content

Instantly share code, notes, and snippets.

@kazuho
Created November 16, 2021 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazuho/0c64c35054548721107e5fa8efba52d1 to your computer and use it in GitHub Desktop.
Save kazuho/0c64c35054548721107e5fa8efba52d1 to your computer and use it in GitHub Desktop.
Command hangs on macOS 11.5 if O_CLOEXEC is used
#include <errno.h>
#include <fcntl.h>
#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define USE_O_CLOEXEC 1
int main(int argc, char **argv)
{
int pipefds[2];
if (pipe(pipefds) != 0) {
fprintf(stderr, "pipe failed:%s\n", strerror(errno));
exit(1);
}
#if USE_O_CLOEXEC
if (fcntl(pipefds[1], F_SETFD, O_CLOEXEC) == -1) {
fprintf(stderr, "fcntl failed:%s\n", strerror(errno));
exit(1);
}
#endif
posix_spawn_file_actions_t actions;
posix_spawn_file_actions_init(&actions);
posix_spawn_file_actions_adddup2(&actions, pipefds[0], 0); /* use pipe as stdin */
posix_spawn_file_actions_addclose(&actions, pipefds[0]); /* close the read-side of the pipe */
#if !USE_O_CLOEXEC
posix_spawn_file_actions_addclose(&actions, pipefds[1]);
#endif
char *cmd[] = {"wc", "-c", NULL};
pid_t pid;
errno = posix_spawnp(&pid, cmd[0], &actions, NULL, cmd, NULL);
/* close the read-side of the pipe */
close(pipefds[0]);
/* write to the pipe and close */
write(pipefds[1], "hello", 5);
close(pipefds[1]);
int stat;
while (waitpid(pid, &stat, 0) != pid)
;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment