我正在开发一个函数,该函数执行特定的 powershell 命令,然后返回输出(如果与 EOF 不同)。该函数第一次正确执行,但第二次输出很奇怪,表明我的代码的某些部分存在缓冲区溢出。我找不到它。否则,我无法针对这种行为找出其他可能的解决方案。
这是代码:
char* buffer_reset(char* buffer);
bool jobsreader (const char* printer_name, char* buffer);
int main (int argc, char *argv[]) {
char buffer[1000];
char* pbuffer = buffer;
jobsreader("Microsoft Print to PDF", pbuffer);
pbuffer = buffer_reset(pbuffer);
jobsreader("Microsoft Print to PDF", pbuffer);
return 0;
}
char* buffer_reset(char* buffer) {
char* memory_reset = &buffer[0];
char* start = memory_reset;
while (*memory_reset != '\0') {
*memory_reset = '\0';
memory_reset++;
}
buffer = start;
return buffer;
}
bool jobsreader (const char* printer_name, char* buffer) {
FILE *output;
const char* cmd = "powershell -Command Get-PrintJob '";
int dim = (strlen(cmd)+1+strlen(printer_name)+1+2);
char powershell[dim]; // + 1 per carattere \0 + 1 per carattere \0 + 2 per stringa "'\0"
strcat(powershell, cmd);
strcat(powershell, printer_name);
strcat(powershell, "'");
fflush(stdout);
printf("%s\n", powershell);
output = popen(powershell, "r"); // Esegue il comando shell e restituisce un puntatore a FILE
if (output == NULL) {
printf("Error in executing the command: are you sure this printer exists?\n");
pclose(output); // Chiude il file
return false;
} else {
char c;
// Se c'è un processo in corso (quindi output della shell diverso da EOF)
while ((c = getc(output)) != EOF) {
*buffer = c;
printf("%c", c); // Stampa a video del processo in corso
buffer++;
}
printf("\n");
*buffer = '\0';
pclose(output); // Chiude il file
return true;
}
}
输出 1:powershell -Command Get-PrintJob 'Microsoft Print to PDF'(确定) 输出 2,3,4 ...:powershe@powershell -Command Get-PrintJob 'Microsoft Print to PDF'(错误)
有人可以帮助我吗?
我想输出并执行以下powershell命令:Get-PrintJob
问题是这两行:
char powershell[dim];
strcat(powershell, cmd);
数组未初始化,其内容不确定。
更具体地说,它不能用作以 null 结尾的字符串,而这正是
strcat
所期望的。因此,你将会有未定义的行为。
您必须以
strcpy
调用开始:
strcpy(powershell, cmd);