/* This file is part of genrc Copyryght (C) 2018 Sergey Poznyakoff License GPLv3+: GNU GPL version 3 or later 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::s///[] Grep for the first line in that matches . 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::s///[];..."); 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; }