#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int system(char *cmd) { int pid = fork(); if (pid < 0) return(-1); if (pid == 0) { execl("/bin/sh", "sh", "-c", cmd, (char *)NULL); perror("/bin/sh"); exit(127); } else { int status; wait(&status); return(WEXITSTATUS(status)); } }
It's not extremely clear what should be done if the wait() fails.
It's quite important that the child process does not return from system(). If the execl() fails, we have to call exit() (or better yet, _exit() — see the man page if interested).