~ruther/CTU-FEE-B0B35APO-Semestral-project

300afb3265af4d9f011b11c50198c9049fa3c6de — František Boháček 3 years ago ab9ad09
feat: add file execute process
2 files changed, 67 insertions(+), 0 deletions(-)

A file-browser/include/file_execute.h
A file-browser/src/file_execute.c
A file-browser/include/file_execute.h => file-browser/include/file_execute.h +17 -0
@@ 0,0 1,17 @@
#include <unistd.h>
#include <stdbool.h>

typedef struct {
  pid_t pid;
  int output_signal;
  bool exited;
} executing_file_t;

typedef struct {
  bool error;
  executing_file_t file;
} executing_file_error_t;

executing_file_error_t executing_file_execute(char *path, char *args);
int executing_file_wait(executing_file_t *file);
bool executing_file_has_ended(executing_file_t *file);

A file-browser/src/file_execute.c => file-browser/src/file_execute.c +50 -0
@@ 0,0 1,50 @@
#include "file_execute.h"
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>

executing_file_error_t executing_file_execute(char *path, char *args) {
  executing_file_error_t ret;
  pid_t pid = fork();

  if (pid == -1) {
    ret.error = true;
    return ret;
  }

  if (pid == 0) {
    execl(path, args, (char*)NULL);
    exit(errno);
  }

  ret.error = false;
  ret.file.pid = pid;
  ret.file.output_signal = 0;
  ret.file.exited = false;
  return ret;
}

int executing_file_wait(executing_file_t *file) {
  pid_t data = waitpid(file->pid, &file->output_signal, 0);
  if (data == -1) {
    return -1;
  }

  file->exited = true;
  return file->output_signal;
}

bool executing_file_has_ended(executing_file_t *file) {
  if (file->exited) {
    return true;
  }

  if (waitpid(file->pid, &file->output_signal, WNOHANG) == 0) {
    file->exited = true;
    return true;
  }

  return false;
}

Do not follow this link