From ddf398dcb672f0b7d06f4d0691763487f21e5bfa Mon Sep 17 00:00:00 2001 From: Lucas Date: Tue, 14 Apr 2026 12:54:40 +0200 Subject: [PATCH] exec_file.c --- AnimalProcessing/Fundamentals/exec.c | 45 +++++++++++++++++++++++ AnimalProcessing/Fundamentals/exec_file.c | 42 +++++++++++++++++++++ 2 files changed, 87 insertions(+) diff --git a/AnimalProcessing/Fundamentals/exec.c b/AnimalProcessing/Fundamentals/exec.c index e69de29..f370bf5 100644 --- a/AnimalProcessing/Fundamentals/exec.c +++ b/AnimalProcessing/Fundamentals/exec.c @@ -0,0 +1,45 @@ +#include +#include +#include +#include +#include +#include +#include + +int execute_me(char *cmd, char **argv){ + + if (!cmd || !argv || !*argv) return 1; + + int wstatus; + + pid_t pid = fork(); + + if (pid < 0) return -1; + + // Child + else if (pid == 0) { + + if (cmd != *argv) exit(-1); + else exit(execvp(cmd, argv)); + } + + // Daddy + else { + + if(waitpid(pid, &wstatus, 0) == -1) return -1; + + if(WIFEXITED(wstatus)) return WEXITSTATUS(wstatus); + + return 0; + } + +} +/* +int main(){ + char *argv[] = {"ls", "-l", NULL}; +int r1 = execute_me("ls", argv); +printf("%d\n", r1); + + int r2 = execute_me("wrong", argv); + printf("%d\n", r2); +}*/ diff --git a/AnimalProcessing/Fundamentals/exec_file.c b/AnimalProcessing/Fundamentals/exec_file.c index e69de29..414eb27 100644 --- a/AnimalProcessing/Fundamentals/exec_file.c +++ b/AnimalProcessing/Fundamentals/exec_file.c @@ -0,0 +1,42 @@ +#include +#include +#include +#include +#include +#include +#include + +int execute_me2(char *file, char **args){ + + if(!file || !args || !*args) return 1; + + int wstatus; + pid_t pid = fork(); + + if (pid < 0) return -1; + + // Child + else if (pid == 0) { + + if(file != *args) exit(-1); + + exit(execlp(file, args[0], args[1], (char *)NULL)); + } + + // Daddy + else { + + if(waitpid(pid, &wstatus, 0) == -1) return -1; + + if(WIFEXITED(wstatus)) return WEXITSTATUS(wstatus); + } + return 0; +} +/* +int main(){ +char *argv[] = {"ls", "-l", NULL}; +execute_me2("ls", argv); // should be the same as doing "ls -l" in the shell + +//char *argv[] = {"ls", "-l", NULL}; +int i = execute_me2("wrong", argv); // should return 255 +}*/