/*-------------------------------------------------------------------*/ /* textforkexecwait.c */ /* The fork, exec, and wait system calls. */ /*-------------------------------------------------------------------*/ #include #include #include #include #define MAX_COMMAND_SIZE 1024 int main(int argc, char *argv[]) { int iPid; int iWaitPid; int iStatus; char pcCommandName[MAX_COMMAND_SIZE]; printf("Enter a command (no arguments, exit to stop): "); scanf("%s", pcCommandName); while (strcmp(pcCommandName, "exit") != 0) { iPid = fork(); if (iPid == -1) { printf("Failed to execute fork.\n"); exit(1); } if (iPid == 0) { char *ppcArgv[2]; ppcArgv[0] = pcCommandName; ppcArgv[1] = NULL; execvp(ppcArgv[0], ppcArgv); printf("Failed to execute execvp.\n"); /* Should never reach. */ exit(1); /* Should never reach. */ } /* Wait for the child process to finish. */ wait(&iStatus); printf("Command executed with status %d.\n\n", WEXITSTATUS(iStatus)); printf("Enter a command (no arguments, exit to stop): "); scanf("%s", pcCommandName); } return 0; } /* Sample execution: $ testforkexecwait Enter a command (no arguments, exit to stop): hello Hello world. Command executed with status 0. Enter a command (no arguments, exit to stop): date Sun Dec 9 21:15:41 EST 2001 Command executed with status 0. Enter a command (no arguments, exit to stop): exit $ */