aboutsummaryrefslogtreecommitdiff
path: root/src/pid_grep.c
blob: 76740ac1fdbed3ba882aaf0a93207ab1031fb431 (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
/* This file is part of genrc
Copyryght (C) 2018 Sergey Poznyakoff
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
*/
#include "genrc.h"

/*
GREP:<FILE>:s/<RX>/<REPL>/[<FLAGS>]

Grep for the first line in <FILE> that matches <RX>. If found, process the
string using the SED expression and return the result.
*/

struct grep_pid_closure {
	struct genrc_pid_closure generic;
	char *filename;
	TRANSFORM tf;
};

static int
pid_grep_get(GENRC_PID_CLOSURE *clos, PIDLIST *plist)
{
	struct grep_pid_closure *grep_clos = (struct grep_pid_closure *)clos;
	FILE *fp;
	char *buf = NULL;
	size_t size = 0;
	ssize_t n;
	char *res = NULL;
	pid_t pid;
	
	fp = fopen(grep_clos->filename, "r");
	if (!fp) {
		if (errno == ENOENT)
			return 0;
		system_error(errno, "can't open file %s", grep_clos->filename);
		return -1;
	}

	while ((n = grecs_getline(&buf, &size, fp)) > 0) {
		buf[--n] = 0;
		if (n == 0)
			continue;
		res = transform_string_if_match(grep_clos->tf, buf);
		if (res)
			break;
	}
	free(buf);
	fclose(fp);

	if (!res) {
		usage_error("%s: no match for %s",
			    grep_clos->filename,
			    grep_clos->generic.name);
		return -1;
	}

	pid = file_read_pid(res);
	free(res);

	if (pid == -1)
		return -1;
	if (pid > 0)
		pidlist_add(plist, pid);
	
	return 0;
}

GENRC_PID_CLOSURE *
genrc_pid_grep_init(int argc, char **argv)
{
	struct grep_pid_closure *clos;
	
	if (argc != 3)
		usage_error("expected format: GREP:<FILE>:s/<RX>/<REPL>/[<FLAGS>];...");

	clos = xmalloc(sizeof(*clos));
	clos->generic.pid = pid_grep_get;
	clos->filename = xstrdup(argv[1]);
	clos->tf = compile_transform_expr(argv[2], REG_EXTENDED);

	return (GENRC_PID_CLOSURE *) clos;
}


Return to:

Send suggestions and report system problems to the System administrator.