/*-------------------------------------------------------------------*/ /* 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 iStatus; char pcCommandName[MAX_COMMAND_SIZE]; printf("testforkexecwait process (%ld)\n", (long)getpid()); fflush(stdout); printf("Enter a command (no arguments, exit to stop): "); fflush(stdout); scanf("%s", pcCommandName); while (strcmp(pcCommandName, "exit") != 0) { iPid = fork(); if (iPid == -1) { perror(argv[0]); return 1; } if (iPid == 0) { char *ppcArgv[2]; ppcArgv[0] = pcCommandName; ppcArgv[1] = NULL; execvp(ppcArgv[0], ppcArgv); perror(argv[0]); _exit(1); } /* Wait for the child process to finish. */ wait(&iStatus); printf("Command executed with status %d.\n\n", WEXITSTATUS(iStatus)); fflush(stdout); printf("Enter a command (no arguments, exit to stop): "); fflush(stdout); scanf("%s", pcCommandName); } return 0; } /* Sample execution: $ gcc -o hello hello.c $ gcc -o testforkexecwait testforkexecwait.c $ testforkexecwait testforkexecwait process (2589) Enter a command (no arguments, exit to stop): hello hello process (2597) Hello world. Command executed with status 0. Enter a command (no arguments, exit to stop): date Wed Apr 24 15:56:29 EDT 2002 Command executed with status 0. Enter a command (no arguments, exit to stop): xxx testforkexecwait: No such file or directory Command executed with status 1. Enter a command (no arguments, exit to stop): exit $ */