2 * setsid.c -- execute a command in a new session
3 * Rick Sladkey <jrs@world.std.com>
4 * In the public domain.
6 * 1999-02-22 Arkadiusz MiĆkiewicz <misiek@pld.ORG.PL>
7 * - added Native Language Support
9 * 2001-01-18 John Fremlin <vii@penguinpowered.com>
10 * - fork in case we are process group leader
12 * 2008-08-20 Daniel Kahn Gillmor <dkg@fifthhorseman.net>
13 * - if forked, wait on child process and emit its return code.
20 #include <sys/ioctl.h>
21 #include <sys/types.h>
26 #include "closestream.h"
28 static void __attribute__((__noreturn__
)) usage(void)
31 fputs(USAGE_HEADER
, out
);
33 " %s [options] <program> [arguments ...]\n"),
34 program_invocation_short_name
);
36 fputs(USAGE_SEPARATOR
, out
);
37 fputs(_("Run a program in a new session.\n"), out
);
39 fputs(USAGE_OPTIONS
, out
);
40 fputs(_(" -c, --ctty set the controlling terminal to the current one\n"), out
);
41 fputs(_(" -f, --fork always fork\n"), out
);
42 fputs(_(" -w, --wait wait program to exit, and use the same return\n"), out
);
44 fprintf(out
, USAGE_HELP_OPTIONS(16));
46 fprintf(out
, USAGE_MAN_TAIL("setsid(1)"));
50 int main(int argc
, char **argv
)
52 int ch
, forcefork
= 0;
57 static const struct option longopts
[] = {
58 {"ctty", no_argument
, NULL
, 'c'},
59 {"fork", no_argument
, NULL
, 'f'},
60 {"wait", no_argument
, NULL
, 'w'},
61 {"version", no_argument
, NULL
, 'V'},
62 {"help", no_argument
, NULL
, 'h'},
66 setlocale(LC_ALL
, "");
67 bindtextdomain(PACKAGE
, LOCALEDIR
);
69 close_stdout_atexit();
71 while ((ch
= getopt_long(argc
, argv
, "+Vhcfw", longopts
, NULL
)) != -1)
86 print_version(EXIT_SUCCESS
);
88 errtryhelp(EXIT_FAILURE
);
91 if (argc
- optind
< 1) {
92 warnx(_("no command specified"));
93 errtryhelp(EXIT_FAILURE
);
96 if (forcefork
|| getpgrp() == getpid()) {
100 err(EXIT_FAILURE
, _("fork"));
108 if (wait(&status
) != pid
)
109 err(EXIT_FAILURE
, "wait");
110 if (WIFEXITED(status
))
111 return WEXITSTATUS(status
);
112 err(status
, _("child %d did not exit normally"), pid
);
117 err(EXIT_FAILURE
, _("setsid failed"));
119 if (ctty
&& ioctl(STDIN_FILENO
, TIOCSCTTY
, 1))
120 err(EXIT_FAILURE
, _("failed to set the controlling terminal"));
121 execvp(argv
[optind
], argv
+ optind
);
122 errexec(argv
[optind
]);