normanr commented on code in PR #1214:
URL:
https://github.com/apache/incubator-nuttx-apps/pull/1214#discussion_r913272734
##########
system/hostname/hostname_main.c:
##########
@@ -42,17 +42,64 @@
int main(int argc, FAR char *argv[])
{
int ret;
+ FILE *f;
+ int maxarg = 2;
char hostname[HOST_NAME_MAX + 1];
if (argc > 1)
{
- if (argc > 2)
+ if (strcmp(argv[1], "-F") == 0)
+ {
+ if (argc < 3)
+ {
+ fprintf(stderr, "ERROR: Option requires an argument -- 'F'\n");
+ return EXIT_FAILURE;
+ }
+
+ f = fopen(argv[2], "r");
+ if (f == NULL)
+ {
+ fprintf(stderr, "ERROR: Failed to open '%s': %s\n", argv[2],
+ strerror(errno));
+ return EXIT_FAILURE;
+ }
+
+ if (fgets(hostname, sizeof(hostname), f) == NULL && (errno != 0))
+ {
+ fclose(f);
+ fprintf(stderr, "ERROR: Failed to read '%s': %s\n", argv[2],
+ strerror(errno));
+ return EXIT_FAILURE;
+ }
+
+ *strchrnul(hostname, '\n') = '\0';
+
+ fclose(f);
+ maxarg = 3;
+ }
+ else if (argv[1][0] == '-')
+ {
+ fprintf(stderr, "ERROR: Invalid option -- '%s'\n", argv[1]);
+ return EXIT_FAILURE;
+ }
+ else
+ {
+ strlcpy(hostname, argv[1], sizeof(hostname));
+ }
+
+ if (argc > maxarg)
{
fprintf(stderr, "ERROR: Too many arguments\n");
return EXIT_FAILURE;
}
- ret = sethostname(argv[1], strlen(argv[1]));
+ if (strlen(hostname) == 0)
Review Comment:
I considered this, and the resulting assembly code is identical. The
compiler optimizes `strlen(hostname) == 0` as `*hostname == '\0'` so I figured
to stick with the more readable version.
I'm not sure if we also want a check for `strlen(hostname) > HOST_NAME_MAX`
(to prevent the supplied hostname being truncated. I would expect that the
compiler should re-use the returned value and not call `strlen(hostname)` twice.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]