我有一个程序来执行一些进程并显示它们的 ID:
主功能:
int main(void){
char code[25];
bool testCmd = false;
DWORD arrProcessID[10];
char *fullCmd;
char *parameter;
char *command;
char *extraCmd;
int loop = 1;
while (loop == 1){
printf("C:\\>");
scanf("%[^\n]",code);
fullCmd = strdup(code);
command = strtok(fullCmd, " ");
extraCmd = strtok(NULL, " ");
parameter = strtok(NULL, " ");
if ((strcmp(command, "list") == 0) || (strcmp(command, "LIST") == 0)){
if (extraCmd != 0){
printf("%s is not recognized as an internal or external command, operable program or batch file. \n", code);
} else {
printf("ID process is running: \n");
printf("%d \n",sizeof(arrProcessID));
for(int i=0; i<sizeof(arrProcessID); i++){
printf("%d : %lu \n", i, arrProcessID[i]);
}
}
}
if ((strcmp(command, "install") == 0) || (strcmp(command, "INSTALL") == 0)){
if (extraCmd == 0){
printf("%s is not recognized as an internal or external command, operable program or batch file. \n", code);
} else {
if ((strcmp(parameter, "-b") == 0) || (strcmp(parameter, "-B") == 0)){
PROCESS_INFORMATION pi = createBackgroundProcess(extraCmd, parameter);
arrProcessID[0] = pi.dwProcessId;
printf("%d \n",sizeof(arrProcessID));
printf("%lu \n",arrProcessID[0]);
}
}
}
if(strcmp(command,"exit") == 0 || strcmp(command, "quit") == 0){
loop = 0;
printf("Program Terminated\n");
}
while(getchar() != '\n');
}
return 0;
}
这是我创建流程的功能:
PROCESS_INFORMATION createBackgroundProcess(char *exeFileName, char *parameter){
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
CreateProcess(exeFileName,NULL,NULL,NULL,FALSE,
CREATE_NO_WINDOW,NULL,NULL,&si,&pi);
TerminateProcess(pi.hProcess, 0);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return pi;
}
但是当我只创建 1 个进程时,我的数组 arrProcessID 总是有 size = 40(总是 = sizeof(arrProcessID) * 4),而我在 arrProcessID[0] 中添加了 1 个值。那么,我的数组发生了什么?