powerPC 中的 pclose 问题
pclose issue in powerPC
我正在为嵌入式系统创建一个应用程序,它使用 popen 到 运行 /usr/bin/find,但是我遇到了一个奇怪的问题,
我的代码类似于...
int main() {
char str[2048]
fun1(str, 2048);
return 0;
}
int fun1(char* str, int cap) {
return fun2(str,<command>, cap);
}
int fun2(char* str, char* cmd, int cap) {
FILE* fptr = popen(cmd, "r");
char line_buffer[2048];
int total = 0;
int count = 0;
str[0] = '[=10=]';
while (count = (fgets(line_buffer, sizeof(line_buffer), fptr)) != 0) {
total += count;
strcat(str, line_buffer);
}
pclose(fptr);
return total;
}
当调用 pclose 时,我的应用程序返回到 main,就像再次调用 main() 一样,这只发生在 PowerPC 上,但不会发生在 ARM 设备上,这是为什么?
my application goes back to main as if main() was called again
如果让我赌一把,我会说你的代码崩溃了,你看到的实际上是一个自动软重置。
但是为什么程序会崩溃?
我认为发生这种情况是因为您调用 strcat()
时没有进行任何绑定检查。您读取的每一行可以长达 2048 字节,而整个连接的字符串也只有 2048 字节长。
可能恰好您的缓冲区定义得太接近 FILE *fptr
,因此它会覆盖它并且 pclose()
尝试关闭无效的处理程序并崩溃。
要验证这是问题所在,请尝试将char str[2048]
更改为char str[65536]
并查看它是否重现。
要解决问题,请使用更安全的 strncat
而不是 strcat
以避免内存损坏。
我正在为嵌入式系统创建一个应用程序,它使用 popen 到 运行 /usr/bin/find,但是我遇到了一个奇怪的问题, 我的代码类似于...
int main() {
char str[2048]
fun1(str, 2048);
return 0;
}
int fun1(char* str, int cap) {
return fun2(str,<command>, cap);
}
int fun2(char* str, char* cmd, int cap) {
FILE* fptr = popen(cmd, "r");
char line_buffer[2048];
int total = 0;
int count = 0;
str[0] = '[=10=]';
while (count = (fgets(line_buffer, sizeof(line_buffer), fptr)) != 0) {
total += count;
strcat(str, line_buffer);
}
pclose(fptr);
return total;
}
当调用 pclose 时,我的应用程序返回到 main,就像再次调用 main() 一样,这只发生在 PowerPC 上,但不会发生在 ARM 设备上,这是为什么?
my application goes back to main as if main() was called again
如果让我赌一把,我会说你的代码崩溃了,你看到的实际上是一个自动软重置。
但是为什么程序会崩溃?
我认为发生这种情况是因为您调用 strcat()
时没有进行任何绑定检查。您读取的每一行可以长达 2048 字节,而整个连接的字符串也只有 2048 字节长。
可能恰好您的缓冲区定义得太接近 FILE *fptr
,因此它会覆盖它并且 pclose()
尝试关闭无效的处理程序并崩溃。
要验证这是问题所在,请尝试将char str[2048]
更改为char str[65536]
并查看它是否重现。
要解决问题,请使用更安全的 strncat
而不是 strcat
以避免内存损坏。