/////////////////////////////////////////////////////////// // Betriebssysteme I - Windows 2000 // Lab 2: A simple command shell // // author: Stephan Brumme // last changes: November 20, 2001 // Win32 API #include // console output (printf etc.) #include int main(int argc, char* argv[]) { // file handle to access the shell commands FILE* fd; // at most 512 characters per line const int MAX_LINE_LEN = 512; char cmdLine[MAX_LINE_LEN+1]; // a shell command file must be supplied if (argc > 2) { printf("usage: \"MinShell ShellCommands.txt\"\n"); printf("or just \"MinShell\" if you want to type in the commands.\n"); // wrong parameter count return 1; } if (argc == 2) { // open file fd = fopen(argv[1], "r"); if (fd == NULL) { printf("Cannot find %s.\n", argv[1]); // failed return 2; } } else { // read from console fd = stdin; printf("Press [Return] to quit.\n\n"); } // read and execute shell commands for (;;) { // prompt printf("MinShell$ "); // read a single command, abort if [Return] was pressed if (fgets(cmdLine, MAX_LINE_LEN, fd) == NULL || cmdLine[0] == 10) { printf("\n... done\n"); return 0; } // strip CR-LF char* pCmdLine = cmdLine; while(*pCmdLine != 0x0A && *pCmdLine != 0x0D && *pCmdLine != 0x00) pCmdLine++; *pCmdLine = 0x00; // show shell command (if not typed in from console) if (fd != stdin) printf("%s\n", cmdLine); // fill in start-up info values STARTUPINFO StartupInfo; ZeroMemory(&StartupInfo, sizeof(StartupInfo)); StartupInfo.cb = sizeof(StartupInfo); // CreateProcess returns some process information PROCESS_INFORMATION ProcessInfo; ZeroMemory(&ProcessInfo, sizeof(ProcessInfo)); if (CreateProcess(NULL, // application name is first token of the command line cmdLine, // contains application name, too NULL, // default process security settings NULL, // default thread security settings FALSE, // process DOES NOT inherit from minshell.exe 0, // child has no access to minshell.exe NULL, // no special environment NULL, // same directory &StartupInfo, &ProcessInfo) == 0) { // error handling const int MAX_ERROR_LEN = 255; char strError[MAX_ERROR_LEN+1]; DWORD nError = GetLastError(); FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, nError, 0, strError, MAX_ERROR_LEN, NULL); printf("Failed to create \"%s\": (%d) %s\n", cmdLine, nError, strError); // failed to execute a program // return 3; } // wait until process terminates and clean up WaitForSingleObject(ProcessInfo.hProcess, INFINITE); CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); } // successful return 0; }