/*-------------------------------------------------------------------*/ /* textforkexec.c */ /* The fork and exec system calls. */ /*-------------------------------------------------------------------*/ #include #include #include #define MAX_COMMAND_SIZE 1024 int main(int argc, char *argv[]) { int iPid; char pcCommandName[MAX_COMMAND_SIZE]; printf("testforkexec 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); } 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 testforkexec testforkexec.c $ testforkexec testforkexec process (2357) Enter a command (no arguments, exit to stop): hello Enter a command (no arguments, exit to stop): hello process (2364) Hello world. date Enter a command (no arguments, exit to stop): Wed Apr 24 15:53:36 EDT 2002 xxx Enter a command (no arguments, exit to stop): testforkexec: No such file or directory exit $ */ /* Note: Malformed! */