summaryrefslogtreecommitdiffstats
path: root/sys-utils/setpgid.c
blob: 936991d65bbe86a49742136e072f1e78c7036c00 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
 * No copyright is claimed.  This code is in the public domain; do with
 * it what you wish.
 *
 * Written by Daan De Meyer <daan.j.demeyer@gmail.com>
 */
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

#include "closestream.h"

static void __attribute__((__noreturn__)) usage(void)
{
	FILE *out = stdout;
	fputs(USAGE_HEADER, out);
	fprintf(out, _(
		" %s [options] <program> [arguments ...]\n"),
		program_invocation_short_name);

	fputs(USAGE_SEPARATOR, out);
	fputs(_("Run a program in a new process group.\n"), out);

	fputs(USAGE_OPTIONS, out);
	fputs(_(" -f, --foregound     Make a foreground process group\n"), out);

	fprintf(out, USAGE_HELP_OPTIONS(16));

	fprintf(out, USAGE_MAN_TAIL("setpgid(1)"));
	exit(EXIT_SUCCESS);
}

int main(int argc, char **argv)
{
	int ch, foreground = 0, fd;
	sigset_t s, old;

	static const struct option longopts[] = {
		{"foreground", no_argument, NULL, 'f'},
		{"version", no_argument, NULL, 'V'},
		{"help", no_argument, NULL, 'h'},
		{NULL, 0, NULL, 0}
	};

	setlocale(LC_ALL, "");
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
	close_stdout_atexit();

	while ((ch = getopt_long(argc, argv, "+Vh", longopts, NULL)) != -1)
		switch (ch) {
		case 'f':
			foreground = 1;
			break;
		case 'h':
			usage();
		case 'V':
			print_version(EXIT_SUCCESS);
		default:
			errtryhelp(EXIT_FAILURE);
		}

	if (argc - optind < 1) {
		warnx(_("no command specified"));
		errtryhelp(EXIT_FAILURE);
	}

	if (setpgid(0, 0) < 0)
		err(EXIT_FAILURE, _("setpgid failed"));

	if (foreground) {
		fd = open("/dev/tty", O_RDONLY|O_CLOEXEC);
		if (fd >= 0) {
			if (sigemptyset(&s) < 0)
				err(EXIT_FAILURE, _("sigemptyset failed"));
			if (sigaddset(&s, SIGTTOU) < 0)
				err(EXIT_FAILURE, _("sigaddset failed"));
			if (sigprocmask(SIG_BLOCK, &s, &old) < 0)
				err(EXIT_FAILURE, _("sigprocmask failed"));
			if (tcsetpgrp(fd, getpgid(0)) < 0)
				err(EXIT_FAILURE, _("tcsetpgrp failed"));
			if (sigprocmask(SIG_SETMASK, &old, NULL) < 0)
				err(EXIT_FAILURE, _("sigprocmask failed"));
		}
	}

	execvp(argv[optind], argv + optind);
	errexec(argv[optind]);
}