Skip to content

Commit e652be0

Browse files
Hao Zengshuahkh
authored andcommitted
cpupower:Fix resource leaks in sysfs_get_enabled()
The sysfs_get_enabled() opened file processor not closed, may cause a file handle leak. Putting error handling and resource cleanup code together makes the code easy to maintain and read. Removed the unnecessary else if branch from the original function, as it should return an error in cases other than '0'. Signed-off-by: Hao Zeng <zenghao@kylinos.cn> Suggested-by: Shuah Khan <skhan@linuxfoundation.org> Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>
1 parent ac9a786 commit e652be0

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

tools/power/cpupower/lib/powercap.c

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -40,25 +40,34 @@ static int sysfs_get_enabled(char *path, int *mode)
4040
{
4141
int fd;
4242
char yes_no;
43+
int ret = 0;
4344

4445
*mode = 0;
4546

4647
fd = open(path, O_RDONLY);
47-
if (fd == -1)
48-
return -1;
48+
if (fd == -1) {
49+
ret = -1;
50+
goto out;
51+
}
4952

5053
if (read(fd, &yes_no, 1) != 1) {
51-
close(fd);
52-
return -1;
54+
ret = -1;
55+
goto out_close;
5356
}
5457

5558
if (yes_no == '1') {
5659
*mode = 1;
57-
return 0;
60+
goto out_close;
5861
} else if (yes_no == '0') {
59-
return 0;
62+
goto out_close;
63+
} else {
64+
ret = -1;
65+
goto out_close;
6066
}
61-
return -1;
67+
out_close:
68+
close(fd);
69+
out:
70+
return ret;
6271
}
6372

6473
int powercap_get_enabled(int *mode)

0 commit comments

Comments
 (0)