The following program:
Code:
#include <stdlib.h>
#include <stdio.h>

int main(void) {
    int status = system("ls /");
    
    if (status == -1) {
        fputs("Error when creating child process or retrieving its exit status.\n", stderr);
    }
    else {
        printf("Child process exited with exit status %d\n", status);
    }
    
    return 0;
}
Is roughly equivalent to the following one using fork() and exec():
Code:
#define _POSIX_C_SOURCE 200809L

#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>

int main(void) {
    pid_t pid = fork();
    
    switch (pid) {
        case -1: // Couldn't create process
            fputs("Couldn't create another process\n", stderr);
            break;
        
        case 0: // Child process
            execlp("ls", "ls", "/", (char *)0);
            fputs("Couldn't replace the child process image\n", stderr);
            break;
            
        default: // Parent process
            ;
            int status;
            pid_t wpid = wait(&status);
            if (wpid == pid) {
                printf("Child process exited with exit status %d\n", status);
            }
    }
    
    return 0;
}
But how could this one be rewritten using fork() and exec()?
Code:
#include <stdlib.h>
#include <stdio.h>

void printstatus(int status) {
    if (status == -1) {
        fputs("Error when creating child process or retrieving its exit status.\n", stderr);
    }
    else {
        printf("Child process exited with exit status %d\n", status);
    }
}

int main(void) {
    int status = system("ls /");
    printstatus(status);
    
    status = system("ls /tmp");
    printstatus(status);
    
    return 0;
}
Basically my question is how to create a second fork of the process and change its flow so that it executes a different command. Or better still, how to create a fork and execute a command specified in an arbitrary string the same way it is passed to system() as an argument.