#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <sys/wait.h>

char *PREFIX = "TEST_SYSTEM";

void message(const char *msg) {
	printf ("%s: %s.\n", PREFIX, msg);
}

int main(int argc, char *argv[]) {
	int exit_code = INT_MAX; 
	if (1 == argc) {
		exit_code = system(NULL);
		if (0 != exit_code) 
			message("shell available");
		else
			message("shell NOT available");
	} else {
		char *cmd = argv[1];
		printf("cmd: `%s`\n", cmd);
		exit_code = system(cmd);
		if (-1 == exit_code) {
			message("could NOT create child process, or could not retrieve its status");
			perror(NULL);
		} else {
			message("child process created and its status retrieved without problem");
			if (WIFEXITED(exit_code)) {
				message("the child terminated normally");
				switch(WEXITSTATUS(exit_code)) {
					case 127:
						/* man system states that the
						 * exit code will by 127 if the
						 * shell cannot be executed, but
						 * man sh says this can also
						 * occur if a command file was
						 * not found. Moreover, if the
						 * user command exits with 127,
						 * then we also end up here. */
						message("the child process could NOT launch a shell, OR command not found, OR user command failed with exit status 127");
						break;
					case 0:
						message("the child process could launch a shell");
						message("the command ran successfully in the shell");
						break;
					default:
						message("the child process could launch a shell");
						message("the command did NOT run successfully in the shell");
						break;
				}
			} else {
				message("the child dit NOT terminate normally");
			}
		}
	}
}
