An answer:

#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));
    }
}

A few grading notes:

"return(status)" was accepted for full marks; the WEXITSTATUS (or writing "status >> 8") is not important as far as your understanding of the material, although of course it is crucial for your program to function in real life.

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).


[press 'back' in your web browser to return to where you were in the exam]