Skip to contentSkip to conversation

trace-cmd: Use open() and not fopen() for set_plugin_instance()

PATCH New Steven Rostedt 1 participant 1 message Mar 25, 2021

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 trace-cmd: Use open() and not fopen() for set_plugin_instance()

From: "Steven Rostedt (VMware)" <[email protected]>

After hitting an error in writing to the "current_tracer" file that was not reported by trace-cmd, it was due to the use of fopen(). Unless otherwise specified, fwrite() will buffer writes, which can hide errors when writing to the file.

Instead use open() and write() where the return gives an immediate result of success or failure. There's no real reason to use fopen() anyway, as the writes are rather trivial.

---
 tracecmd/trace-record.c | 30 +++++++++++++++++-------------
 1 file changed, 17 insertions(+), 13 deletions(-)
tracecmd/trace-record.c +17 -13
index a0eb0385..4b57236b 100644
@@ -1653,16 +1653,17 @@ static void run_cmd(enum trace_type type, const char *user, int argc, char **arg
 static void
 set_plugin_instance(struct buffer_instance *instance, const char *name)
 {
-	FILE *fp;
 	char *path;
 	char zero = '0';
+	int ret;
+	int fd;
 
 	if (is_guest(instance))
 		return;
 
 	path = tracefs_instance_get_file(instance->tracefs, "current_tracer");
-	fp = fopen(path, "w");
-	if (!fp) {
+	fd = open(path, O_WRONLY);
+	if (fd < 0) {
 		/*
 		 * Legacy kernels do not have current_tracer file, and they
 		 * always use nop. So, it doesn't need to try to change the
@@ -1672,12 +1673,15 @@ set_plugin_instance(struct buffer_instance *instance, const char *name)
 			tracefs_put_tracing_file(path);
 			return;
 		}
-		die("writing to '%s'", path);
+		die("Opening '%s'", path);
 	}
-	tracefs_put_tracing_file(path);
+	ret = write(fd, name, strlen(name));
+	close(fd);
 
-	fwrite(name, 1, strlen(name), fp);
-	fclose(fp);
+	if (ret < 0)
+		die("writing to '%s'", path); 
+
+	tracefs_put_tracing_file(path);
 
 	if (strncmp(name, "function", 8) != 0)
 		return;
@@ -1685,12 +1689,12 @@ set_plugin_instance(struct buffer_instance *instance, const char *name)
 	/* Make sure func_stack_trace option is disabled */
 	/* First try instance file, then top level */
 	path = tracefs_instance_get_file(instance->tracefs, "options/func_stack_trace");
-	fp = fopen(path, "w");
-	if (!fp) {
+	fd = open(path, O_WRONLY);
+	if (fd < 0) {
 		tracefs_put_tracing_file(path);
 		path = tracefs_get_tracing_file("options/func_stack_trace");
-		fp = fopen(path, "w");
-		if (!fp) {
+		fd = open(path, O_WRONLY);
+		if (fd < 0) {
 			tracefs_put_tracing_file(path);
 			return;
 		}
@@ -1701,8 +1705,8 @@ set_plugin_instance(struct buffer_instance *instance, const char *name)
 	 */
 	add_reset_file(path, "0", RESET_HIGH_PRIO);
 	tracefs_put_tracing_file(path);
-	fwrite(&zero, 1, 1, fp);
-	fclose(fp);
+	write(fd, &zero, 1);
+	close(fd);
 }
 
 static void set_plugin(const char *name)
Signature · 1 line
2.25.4