]>
git.gir.st - forkaftergrep.git/blob - fag.c
1 /* forkaftergrep (C) 2017 Tobias Girstmair, GPLv3 */
3 #define _XOPEN_SOURCE 500
16 struct opt opts
= {0, 0, 0, NULL
, NULL
, STDOUT_FILENO
};
18 int main (int argc
, char** argv
) {
22 /* the `+' forces getopt to stop at the first non-option */
23 while ((opt
= getopt (argc
, argv
, "+t:k::eVhv")) != -1) {
26 opts
.timeout
= atoi (optarg
);
29 opts
.kill_sig
= optarg
? atoi (optarg
) : SIGTERM
;
32 opts
.stream
= STDERR_FILENO
;
38 fprintf (stderr
, VERTEXT USAGE
40 "\t-t N\ttimeout after N seconds\n"
41 "\t-k [M]\tsend signal M to child after timeout (default: 15/SIGTERM)\n"
42 "\t-e\tgrep on stderr instead of stdout\n", argv
[0]);
45 fprintf (stderr
, VERTEXT
);
48 fprintf (stderr
, "Unrecognized option: %c\n" USAGE
, optopt
, argv
[0]);
53 /* the first non-option argument is the search string */
55 opts
.pattern
= argv
[optind
++];
57 fprintf (stderr
, USAGE
"(Missing PATTERN)\n", argv
[0]);
61 /* the remaining are the program to be run */
63 opts
.argv
= &(argv
[optind
]);
65 fprintf (stderr
, USAGE
"(Missing PROGRAM)\n", argv
[0]);
69 int retval
= fork_after_grep (opts
);
74 int fork_after_grep (struct opt opts
) {
82 struct timeval begin
, now
, diff
;
84 if (pipe(pipefd
) == -1) {
85 fprintf (stderr
, "pipe error\n");
89 if ((cpid
= fork()) == -1) {
90 fprintf (stderr
, "fork error: %s", strerror (errno
));
98 dup2 (pipefd
[1], opts
.stream
);
100 close (opts
.stream
==STDOUT_FILENO
?STDERR_FILENO
:STDOUT_FILENO
);
102 if (setsid () == -1) {
103 fprintf (stderr
, "setsid error: %s", strerror (errno
));
107 execvp (opts
.argv
[0], opts
.argv
);
108 fprintf (stderr
, "exec error: %s", strerror (errno
));
109 _exit (EX_UNAVAILABLE
);
112 fcntl (pipefd
[0], F_SETFL
, fcntl (pipefd
[0], F_GETFL
, 0) | O_NONBLOCK
);
114 gettimeofday (&begin
, NULL
);
118 memset (buf
, 0, BUF_SIZE
);
119 nbytes
= read (pipefd
[0], buf
, BUF_SIZE
);
125 fprintf (stderr
, "read error: %s", strerror (errno
));
130 } else if (nbytes
== 0) {
131 fprintf (stderr
, "Child program exited prematurely.\n");
134 if (waitpid (cpid
, &status
, WNOHANG
) > 0 && WIFEXITED (status
)) {
135 return WEXITSTATUS (status
);
137 return EX_UNAVAILABLE
;
140 fputs (buf
, opts
.stream
==STDERR_FILENO
?stderr
:stdout
);
142 if (strstr (buf
, opts
.pattern
) != NULL
) {
143 printf ("%d\n", cpid
);
144 /* create a new child to keep pipe alive (will exit with exec'd program) */
146 while (kill(cpid
, 0) != -1 && errno
!= ESRCH
) sleep (1);
156 if (opts
.timeout
> 0) {
157 gettimeofday (&now
, NULL
);
158 timersub (&now
, &begin
, &diff
);
159 if (diff
.tv_sec
>= opts
.timeout
) {
160 fprintf (stderr
, "Timeout reached. \n");
161 if (opts
.kill_sig
> 0) kill (cpid
, opts
.kill_sig
);
164 return EX_UNAVAILABLE
;