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

ref: 47ee5b137cd9ca1d308dd09c90e07cc96b2fe150 CTU-FEE-B0B35APO-Semestral-project/file-browser/src/file_execute.c -rw-r--r-- 1.7 KiB
47ee5b13 — František Boháček fix: macro long types 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "file_execute.h"
#include "file_access.h"
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>

executing_file_error_t executing_file_execute(char *path, char *args) {
  executing_file_error_t ret;
  executing_file_t file;

  if (pipe(file.stderr_pipe) == -1) {
    ret.error = file_operation_error_from_errno(errno);
    return ret;
  }

  pid_t pid = fork();

  if (pid == -1) {
    close(file.stderr_pipe[0]);
    close(file.stderr_pipe[1]);

    ret.error = true;
    return ret;
  }

  if (pid == 0) { // child process
    close(file.stderr_pipe[READ_END]);

    if(dup2(file.stderr_pipe[WRITE_END], STDERR_FILENO) == -1) {
      perror("There was an error during dup2");
      exit(errno);
    }

    execl(path, path, args, (char*)NULL);

    // Is reached only in case of an error
    fprintf(stderr, "Could not execute file: %s\r\n",
            fileaccess_get_error_text(file_operation_error_from_errno(errno)));
    exit(errno);
  }

  // parent process
  close(file.stderr_pipe[WRITE_END]);

  ret.error = false;
  ret.file = file;
  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;
}

void executing_file_destroy(executing_file_t *file) {
  close(file->stderr_pipe[READ_END]);
}
Do not follow this link