diff mbox series

tools/gpio: prevent resource leak

Message ID 20231109085419.84948-1-heminhong@kylinos.cn
State New
Headers show
Series tools/gpio: prevent resource leak | expand

Commit Message

heminhong Nov. 9, 2023, 8:54 a.m. UTC
In the main() function, the open() function is used to open the file.
When the file is successfully opened, fd is used to interact with the file,
but the fd is not closed, it will cause resource leak.

Signed-off-by: heminhong <heminhong@kylinos.cn>
---
 tools/gpio/gpio-watch.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
diff mbox series

Patch

diff --git a/tools/gpio/gpio-watch.c b/tools/gpio/gpio-watch.c
index 41e76d244192..162c2a8f07c8 100644
--- a/tools/gpio/gpio-watch.c
+++ b/tools/gpio/gpio-watch.c
@@ -42,11 +42,14 @@  int main(int argc, char **argv)
 		memset(&req, 0, sizeof(req));
 
 		req.offset = strtoul(argv[j], &end, 0);
-		if (*end != '\0')
+		if (*end != '\0') {
+			close(fd);
 			goto err_usage;
+		}
 
 		ret = ioctl(fd, GPIO_V2_GET_LINEINFO_WATCH_IOCTL, &req);
 		if (ret) {
+			close(fd);
 			perror("unable to set up line watch");
 			return EXIT_FAILURE;
 		}
@@ -58,6 +61,7 @@  int main(int argc, char **argv)
 	for (;;) {
 		ret = poll(&pfd, 1, 5000);
 		if (ret < 0) {
+			close(pfd.fd);
 			perror("error polling the linechanged fd");
 			return EXIT_FAILURE;
 		} else if (ret > 0) {
@@ -66,7 +70,7 @@  int main(int argc, char **argv)
 			if (rd < 0 || rd != sizeof(chg)) {
 				if (rd != sizeof(chg))
 					errno = EIO;
-
+				close(pfd.fd);
 				perror("error reading line change event");
 				return EXIT_FAILURE;
 			}
@@ -82,6 +86,7 @@  int main(int argc, char **argv)
 				event = "config changed";
 				break;
 			default:
+				close(pfd.fd);
 				fprintf(stderr,
 					"invalid event type received from the kernel\n");
 				return EXIT_FAILURE;
@@ -91,7 +96,7 @@  int main(int argc, char **argv)
 			       chg.info.offset, event, (uint64_t)chg.timestamp_ns);
 		}
 	}
-
+	close(pfd.fd);
 	return 0;
 
 err_usage: