Capture stdout across one cbm_cmd_config invocation. Returns the command's * rc and copies captured stdout (NUL-terminated, truncated to cap) out. * tmpfile+dup2+rewind is the file's established portable capture idiom — * pread/mkstemp/setenv do not exist on the MinGW leg. */
| 11538 | * tmpfile+dup2+rewind is the file's established portable capture idiom — |
| 11539 | * pread/mkstemp/setenv do not exist on the MinGW leg. */ |
| 11540 | static int cli_config_cmd_capture(int argc, char **argv, char *out, size_t cap) { |
| 11541 | out[0] = '\0'; |
| 11542 | FILE *capture = tmpfile(); |
| 11543 | int saved = capture ? dup(fileno(stdout)) : -1; |
| 11544 | if (!capture || saved < 0) { |
| 11545 | if (capture) |
| 11546 | fclose(capture); |
| 11547 | if (saved >= 0) |
| 11548 | close(saved); |
| 11549 | return -1000; |
| 11550 | } |
| 11551 | fflush(stdout); |
| 11552 | if (dup2(fileno(capture), fileno(stdout)) < 0) { |
| 11553 | fclose(capture); |
| 11554 | close(saved); |
| 11555 | return -1000; |
| 11556 | } |
| 11557 | int rc = cbm_cmd_config(argc, argv); |
| 11558 | fflush(stdout); |
| 11559 | (void)dup2(saved, fileno(stdout)); |
| 11560 | close(saved); |
| 11561 | rewind(capture); |
| 11562 | size_t got = fread(out, 1, cap - 1, capture); |
| 11563 | out[got] = '\0'; |
| 11564 | fclose(capture); |
| 11565 | return rc; |
| 11566 | } |
| 11567 | |
| 11568 | /* The user-facing config contract (#1522 bug 2): `get` of an UNSET key prints |
| 11569 | * that key's real default — the same fallback the runtime readers use — with |
no test coverage detected