Move wait_for_pid_to_exit_synchronously and exit_if_pid_has_finished to process_handling.c

This commit is contained in:
Konstantin Pereiaslov
2023-09-04 01:37:51 -05:00
parent f32da29ab9
commit 7e2725aad1
3 changed files with 42 additions and 21 deletions

21
main.c
View File

@@ -54,18 +54,6 @@ void print_version() {
printf("runwhenidle %s\n", VERSION);
}
void exit_if_pid_has_finished(pid_t pid) {
int status;
if (debug) fprintf(stderr, "Checking if PID %i has finished\n", pid);
if (waitpid(pid, &status, WNOHANG + WUNTRACED) == pid && WIFEXITED(status)) {
int exit_code = WEXITSTATUS(status);
if (verbose) {
fprintf(stderr, "PID %i has finished with exit code %u\n", pid, exit_code);
}
exit(exit_code);
}
}
char *read_remaining_arguments_as_char(int argc,
char *const *argv) {
if (optind == argc) { //there is one argument remaining
@@ -110,16 +98,7 @@ long unsigned query_user_idle_time()
return IDLE_TIME_NOT_AVAILABLE_VALUE;
}
int wait_for_pid_to_exit_synchronously(int pid) {
int status;
waitpid(pid, &status, 0);
int exit_code = WEXITSTATUS(status);
if (verbose) {
fprintf(stderr, "PID %i has finished with exit code %u\n", pid, exit_code);
}
return exit_code;
}
int handle_interruption() {
if (command_paused) {
if (verbose) {

View File

@@ -3,6 +3,7 @@
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include "process_handling.h"
#include "output_settings.h"
@@ -72,3 +73,28 @@ void resume_command(pid_t pid) {
}
send_signal_to_pid(pid, SIGCONT, "SIGCONT");
}
int wait_for_pid_to_exit_synchronously(int pid) {
int status;
waitpid(pid, &status, 0);
int exit_code = WEXITSTATUS(status);
if (verbose) {
fprintf(stderr, "PID %i has finished with exit code %u\n", pid, exit_code);
}
return exit_code;
}
void exit_if_pid_has_finished(pid_t pid) {
int status;
if (debug) fprintf(stderr, "Checking if PID %i has finished\n", pid);
if (waitpid(pid, &status, WNOHANG + WUNTRACED) == pid && WIFEXITED(status)) {
int exit_code = WEXITSTATUS(status);
if (verbose) {
fprintf(stderr, "PID %i has finished with exit code %u\n", pid, exit_code);
}
exit(exit_code);
}
}

View File

@@ -30,4 +30,20 @@ void resume_command(pid_t pid);
* @return The PID of the child process on success,
*/
pid_t run_shell_command(const char *shell_command_to_run);
/**
* Waits for a specific process to exit synchronously and returns its exit code.
*
* @param pid The process ID (PID) of the target process to wait for.
* @return The exit code of the process
*/
int wait_for_pid_to_exit_synchronously(int pid);
/**
* Checks if a specific process has finished and exits the current process with the same exit code if it has.
* This function does not block and returns immediately if the process has not finished.
*
* @param pid The process ID (PID) of the target process to check.
*/
void exit_if_pid_has_finished(pid_t pid);
#endif //RUNWHENIDLE_PROCESS_HANDLING_H