1 |
/* $Id: min_shell.c,v 1.3 2006/06/15 13:21:05 joko Exp $ */ |
2 |
|
3 |
#include <stdlib.h> |
4 |
#include <stdio.h> |
5 |
#include <errno.h> |
6 |
#include <windows.h> |
7 |
|
8 |
#include "min_shell.h" |
9 |
|
10 |
#define BOOL int |
11 |
#define TRUE 1 |
12 |
#define FALSE 0 |
13 |
|
14 |
|
15 |
#define MAX_COMMAND_LENGTH 1024 |
16 |
|
17 |
int main(int argc, char * argv[]) { |
18 |
if (argc == 1) { |
19 |
//printf("No arguments given."); |
20 |
//exit(EXIT_FAILURE); |
21 |
char filename[255] = "abc\0"; |
22 |
BOOL background = 0; |
23 |
start_process(filename, background); |
24 |
} |
25 |
|
26 |
if (argc == 2) { |
27 |
FILE * script = fopen(argv[1], "r"); |
28 |
read_commands(script); |
29 |
fclose(script); |
30 |
} |
31 |
} |
32 |
|
33 |
void read_commands(FILE * fp) { |
34 |
|
35 |
char command[MAX_COMMAND_LENGTH]; |
36 |
int command_length; |
37 |
|
38 |
fgets(command, MAX_COMMAND_LENGTH, fp); |
39 |
command_length = strlen(command); |
40 |
|
41 |
/* if last char is newline, strip it */ |
42 |
if (command[command_length-1] == '\n') { |
43 |
command[command_length-1] = '\0'; |
44 |
} |
45 |
|
46 |
process_command(command); |
47 |
} |
48 |
|
49 |
void process_command(char * command) { |
50 |
printf("process_command: %s\n", command); |
51 |
start_process(command, 0); |
52 |
} |
53 |
|
54 |
BOOL start_process(char * filename, BOOL background) { |
55 |
|
56 |
STARTUPINFO si; |
57 |
PROCESS_INFORMATION pi; |
58 |
|
59 |
printf("start_process: '%s'\n", filename); |
60 |
|
61 |
ZeroMemory(&si,sizeof(si)); |
62 |
si.cb = sizeof(STARTUPINFO); |
63 |
|
64 |
ZeroMemory(&pi,sizeof(pi)); |
65 |
//pi.cb=sizeof(PROCESS_INFORMATION); |
66 |
|
67 |
CreateProcess( |
68 |
//"C:\windows\system32\notepad.exe", NULL, |
69 |
//"C:\\windows\\system32\\notepad.exe", NULL, |
70 |
NULL, filename, |
71 |
NULL, NULL, FALSE, 0, |
72 |
NULL, NULL, |
73 |
&si, |
74 |
&pi |
75 |
); |
76 |
check_alert_error("CreateProcess"); |
77 |
|
78 |
if (!background) { |
79 |
long status; |
80 |
status = WaitForSingleObject(pi.hProcess, INFINITE); |
81 |
if (status == WAIT_FAILED) { |
82 |
check_alert_error("WaitForSingleObject"); |
83 |
return FALSE; |
84 |
} |
85 |
} |
86 |
|
87 |
return TRUE; |
88 |
|
89 |
} |
90 |
|
91 |
void check_alert_error(const char * error_source) { |
92 |
DWORD dwError = GetLastError(); |
93 |
|
94 |
HLOCAL message = NULL; |
95 |
BOOL fOk; |
96 |
|
97 |
if (dwError == 0) |
98 |
return; |
99 |
|
100 |
fOk = FormatMessage( |
101 |
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, |
102 |
NULL, |
103 |
dwError, |
104 |
MAKELANGID(LANG_NEUTRAL, SUBLANG_SYS_DEFAULT), |
105 |
(PTSTR)&message, |
106 |
0, |
107 |
NULL |
108 |
); |
109 |
|
110 |
if (message != NULL) { |
111 |
fprintf(stderr, "Error with '%s': %s (Code %i)\n", error_source, message, dwError); |
112 |
LocalFree(message); |
113 |
} |
114 |
|
115 |
} |