diff --git a/include/process.h b/include/process.h index c0b94d8..fb55102 100644 --- a/include/process.h +++ b/include/process.h @@ -35,6 +35,12 @@ int process_parse_status(pid_t pid, process_status_t* status); // find any process that matches name, case insensitive. // list pointer must point to NULL-initialized pointer, and count pointer must pount to initialized 0 // will skip any process which status couldn't be parsed +// deallocate list with free later int processes_by_name(const char* name, process_status_t** list, size_t* count); +// will determine parent process amongst children and set parent pointer to element in list +// process list must consist of parent and children processes, +// obtained from processes_by_name call. of course parent pointer shouldn't be NULL +int determine_parent_process(process_status_t* list, size_t count, process_status_t** parent); + #endif \ No newline at end of file diff --git a/src/main.c b/src/main.c index 9f61ac6..8c022eb 100644 --- a/src/main.c +++ b/src/main.c @@ -24,8 +24,15 @@ int main(int argc, char** argv) size_t count = 0; processes_by_name("dummy_target", &list, &count); - for (size_t i = 0; i < count; i++) - print_process(&list[i]); + process_status_t* parent; + if (determine_parent_process(list, count, &parent)) + { + fputs("unable to determine parent process. exiting", stderr); + free(list); + return 1; + } + + print_process(parent); free(list); return 0; diff --git a/src/process.c b/src/process.c index 68139c9..1a69600 100644 --- a/src/process.c +++ b/src/process.c @@ -111,4 +111,29 @@ int processes_by_name(const char* name, process_status_t** list, size_t* count) closedir(proc); return 0; +} + +static process_status_t* process_by_pid_in_list(pid_t pid, process_status_t* list, size_t count) +{ + for (size_t i = 0; i < count; i++) + if (list[i].pid == pid) return &list[i]; + + return NULL; +} + +int determine_parent_process(process_status_t* list, size_t count, process_status_t** parent) +{ + // we're gonna find any process that doesnt have parent in this list, + // that means we hit real parent, not descendant + for (size_t i = 0; i < count; i++) + { + if (!process_by_pid_in_list(list[i].ppid, list, count)) + { + // that's real parent + *parent = &list[i]; + return 0; + } + } + + return 1; } \ No newline at end of file