]>
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, 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::ehv")) != -1) {
26 opts
.timeout
= atoi (optarg
);
29 opts
.kill_sig
= optarg
? atoi (optarg
) : SIGTERM
;
32 opts
.stream
= STDERR_FILENO
;
35 fprintf (stderr
, VERTEXT USAGE
37 "\t-t N\ttimeout after N seconds\n"
38 "\t-k [M]\tsend signal M to child after timeout (default: 15/SIGTERM)\n"
39 "\t-e\tgrep on stderr instead of stdout\n", argv
[0]);
42 fprintf (stderr
, VERTEXT
);
45 fprintf (stderr
, "Unrecognized option: %c\n" USAGE
, optopt
, argv
[0]);
50 /* the first non-option argument is the search string */
52 opts
.pattern
= argv
[optind
++];
54 fprintf (stderr
, USAGE
"(Missing PATTERN)\n", argv
[0]);
58 /* the remaining are the program to be run */
60 opts
.argv
= &(argv
[optind
]);
62 fprintf (stderr
, USAGE
"(Missing PROGRAM)\n", argv
[0]);
66 int retval
= fork_after_grep (opts
);
71 int fork_after_grep (struct opt opts
) {
72 printf ("timeout:\t%d\n" "kill_sig:\t%d\n" "pattern: \t%s\n" "stream: \t%d\n" "program: \t"
73 , opts
.timeout
, opts
.kill_sig
, opts
.pattern
, opts
.stream
);
74 for (char** p
= opts
.argv
; *p
;) printf ("%s ", *p
++); putchar ('\n');
83 struct timeval begin
, now
, diff
;
85 if (pipe(pipefd
) == -1) {
86 fprintf (stderr
, "pipe error\n");
90 if ((cpid
= fork()) == -1) {
91 fprintf (stderr
, "fork error: %s", strerror (errno
));
99 dup2 (pipefd
[1], opts
.stream
);
101 close (opts
.stream
==STDOUT_FILENO
?STDERR_FILENO
:STDOUT_FILENO
);
103 if (setsid () == -1) {
104 fprintf (stderr
, "setsid error: %s", strerror (errno
));
108 execvp (opts
.argv
[0], opts
.argv
);
109 fprintf (stderr
, "exec error: %s", strerror (errno
));
110 _exit (EX_UNAVAILABLE
);
113 fcntl (pipefd
[0], F_SETFL
, fcntl (pipefd
[0], F_GETFL
, 0) | O_NONBLOCK
);
115 gettimeofday (&begin
, NULL
);
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
;
139 if (strstr (buf
, opts
.pattern
) != NULL
) {
140 printf ("%d\n", cpid
);
141 /* create a new child to keep pipe alive (will exit with exec'd program) */
143 while (kill(cpid
, 0) != -1 && errno
!= ESRCH
) sleep (1);
146 //close(0);close(1);close(2);
151 //close(0);close(1);close(2);
155 if (opts
.timeout
> 0) {
156 gettimeofday (&now
, NULL
);
157 timersub (&now
, &begin
, &diff
);
158 if (diff
.tv_sec
>= opts
.timeout
) {
159 fprintf (stderr
, "Timeout reached. \n");
160 if (opts
.kill_sig
> 0) kill (cpid
, opts
.kill_sig
);
163 return EX_UNAVAILABLE
;