exec_file.c

This commit is contained in:
2026-04-14 12:54:40 +02:00
parent 17a9d00b03
commit ddf398dcb6
2 changed files with 87 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <err.h>
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);
}*/
+42
View File
@@ -0,0 +1,42 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <err.h>
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
}*/