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(_(" -w, --wait wait program to exit, and use the same return\n"), out
);
43 printf(USAGE_HELP_OPTIONS(16));
45 printf(USAGE_MAN_TAIL("setsid(1)"));
49 int main(int argc
, char **argv
)
56 static const struct option longopts
[] = {
57 {"ctty", no_argument
, NULL
, 'c'},
58 {"wait", no_argument
, NULL
, 'w'},
59 {"version", no_argument
, NULL
, 'V'},
60 {"help", no_argument
, NULL
, 'h'},
64 setlocale(LC_ALL
, "");
65 bindtextdomain(PACKAGE
, LOCALEDIR
);
69 while ((ch
= getopt_long(argc
, argv
, "+Vhcw", longopts
, NULL
)) != -1)
72 printf(UTIL_LINUX_VERSION
);
83 errtryhelp(EXIT_FAILURE
);
86 if (argc
- optind
< 1) {
87 warnx(_("no command specified"));
88 errtryhelp(EXIT_FAILURE
);
91 if (getpgrp() == getpid()) {
95 err(EXIT_FAILURE
, _("fork"));
103 if (wait(&status
) != pid
)
104 err(EXIT_FAILURE
, "wait");
105 if (WIFEXITED(status
))
106 return WEXITSTATUS(status
);
107 err(status
, _("child %d did not exit normally"), pid
);
112 err(EXIT_FAILURE
, _("setsid failed"));
114 if (ctty
&& ioctl(STDIN_FILENO
, TIOCSCTTY
, 1))
115 err(EXIT_FAILURE
, _("failed to set the controlling terminal"));
116 execvp(argv
[optind
], argv
+ optind
);
117 err(EXIT_FAILURE
, _("failed to execute %s"), argv
[optind
]);