- 论坛徽章:
- 0
|
哪位大虾帮忙看看,为什么程序结束时会出现段错误
- #include <stdio.h>
- main(){
- char *cpu_usage;
- char* cpu(char *usage);
- cpu(cpu_usage);
-
- printf ("%s\n",cpu_usage);
- printf ("ok\n");
-
- }
- char* cpu(char *usage)
- {
- unsigned int total,total1,total2;
- float user1,user2,nice1,nice2,system1,system2,idle1,idle2;
- float user,nice,system,idle;
- char cpu[100];
- char text[201];
- FILE *fp;
- fp = fopen("/proc/stat", "r");
- while (fgets(text, 200, fp))
- {
- if (strstr(text, "cpu "))
- {
- printf ("%s\n",text);
- sscanf(text, "%s %f %f %f %f", cpu, &user1, &nice1, &system1, &idle1);
- }
- }
- fclose(fp);
- total1 = (user1 + nice1 + system1 + idle1);
-
- sleep(1);
- fp = fopen("/proc/stat", "r");
- while (fgets(text, 200, fp))
- {
- if (strstr(text, "cpu "))
- {
- printf ("%s\n",text);
- sscanf(text, "%s %f %f %f %f", cpu, &user2, &nice2, &system2, &idle2);
- }
- }
- fclose(fp);
- total2 = (user2 + nice2 + system2 + idle2);
-
- user = 100*(user2 - user1)/(total2 - total1);
- system = 100*(system2 - system1)/(total2 - total1);
- idle = 100-user-system;
- sprintf(usage, "%4.2f%,%4.2f%,%4.2f%", user, system, idle);
- printf ("%s\n",usage);
- return usage;
- }
复制代码
运行结果:
- cpu 4490243 13506 2033119 363362296
- cpu 4490243 13506 2033121 363362496
- 0.00%,1.03%,98.97%
- 0.00%,1.03%,98.97%
- ok
- 段错误
复制代码 |
|