From a832a98eac303f11a147f4576325fdec56359799 Mon Sep 17 00:00:00 2001 From: cbdev Date: Sun, 2 Jul 2023 21:12:16 +0200 Subject: Implement reaping --- command.c | 41 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/command.c b/command.c index 17aa5ff..305664b 100644 --- a/command.c +++ b/command.c @@ -3,6 +3,9 @@ #include #include #include +#include +#include +#include #include "nfcommander.h" #include "command.h" @@ -34,7 +37,7 @@ int command_handle(int fd){ && fd == commands[n].iopipe[0]){ bytes = read(fd, input_buffer, sizeof(input_buffer)); if(bytes < 0){ - perror("command/recv"); + perror("cmd/recv"); } else if(bytes == 0){ printf("Command %lu pipe closed\n", n); @@ -43,7 +46,8 @@ int command_handle(int fd){ commands[n].iopipe[0] = -1; } else{ - printf("%d bytes from command %lu\n", bytes, n); + //TODO handle + printf("%d bytes from command %lu: %s\n", bytes, n, input_buffer); } return 0; } @@ -54,8 +58,32 @@ int command_handle(int fd){ } void command_reap(){ - //TODO - printf("Reaping children\n"); + int wait_status; + pid_t status; + size_t n; + + do { + status = waitpid(-1, &wait_status, WNOHANG); + if(status < 0 && errno != ECHILD){ + perror("cmd/reap"); + } + if(status <= 0){ + return; + } + + //find matching command + if(status){ + for(n = 0; n < ncommands; n++){ + if(commands[n].child == status){ + commands[n].flags = 0; + commands[n].child = -1; + close(commands[n].iopipe[0]); + commands[n].iopipe[0] = -1; + printf("Command %lu terminated\n", n); + } + } + } + } while(status); } static int command_spawn(command_t* cmd, char* command_name, char* command_static, size_t arg_length){ @@ -68,6 +96,10 @@ static int command_spawn(command_t* cmd, char* command_name, char* command_stati return 1; } + if(fcntl(cmd->iopipe[0], F_SETFD, FD_CLOEXEC)){ + perror("cmd/fcntl"); + } + cmd->child = fork(); switch(cmd->child){ case -1: @@ -84,7 +116,6 @@ static int command_spawn(command_t* cmd, char* command_name, char* command_stati while((dup2(cmd->iopipe[1], STDOUT_FILENO) == -1) && (errno == EINTR)) { } close(cmd->iopipe[1]); - close(cmd->iopipe[0]); execl(command_name, command_static, NULL); perror("cmd/exec"); _exit(1); -- cgit v1.2.3