I have to develop my own C function system
. To do that, I use the call-system fork
to create a child process and it has to execute the command given to system
, calling exec
.
What I've wrote seems to work fine (it compiles and executes without any error).
The problem concerns my function system
's return (called mySystem
in my code). For example, in my child process, if I give an nonexistent shell to exec
(the latter returns -1), my child process stops with an exit code of -1 because I told it to do that. But : my parent process, which retrieves this exit code thanks to a wait(&status)
, returns... 255 and not -1 !
I don't understand why. I paid attention to use the macro WEXISTATUS in my mySystem
's return.
Could you help me to know why my parent process doesn't return -1 (the exit code of its child process) please ? Thank you in advance.
My src (there are a lot of comments) :
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
pid_t pid;
int mySystem(char*);
int main(int argc, char* argv[]) {
int result = mySystem("ls");
fprintf(stdout, "%i", result);
return 0;
}
int mySystem(char* command) {
pid = fork();
if(pid == -1) {
perror("Fork");
return -1; // An error occurred => return -1
} else if (pid == 0) { // The child process will do the following
execl("BLABLABLABLA MAUVAIS SHELL BLABLABLAA", "sh", "-c", command, NULL); // If this call doesn't fail, the following lines are not read
perror("Exec"); // If (and only if) execl couldn't be called (bad shell's path, etc.)...
exit(-1); // ..., we stop the child process and this one has an exit code equaled to -1
}
/*
* NOW, the child process ended because... :
* 1. Either because of our "exit(-1)" after the "perror" (our source-code)
* 2. OR because of an "exit(-1") of the command passed into the execl (source-code of the execl's command)
* 3. OR because of the "exit(0)" of the command passed into the execl (source-code of the execl's command)
*/
// The parent process will execute the following lines (child process ended)
int status = -1;
if(wait(&status) == -1) { // We store into the var 'status' the exit code of the child process : -1 or 0
perror("Wait"); // Note that because we have only one process child, we don't need to do : while(wait(&status) > 0) {;;}
return -1;
}
return WEXITSTATUS(status); // Our function mySystem returns this exit code
}