1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include "sd-journal.h"
12 #include "alloc-util.h"
14 #include "main-func.h"
15 #include "parse-util.h"
16 #include "pretty-print.h"
17 #include "string-util.h"
18 #include "syslog-util.h"
21 static const char *arg_identifier
= NULL
;
22 static int arg_priority
= LOG_INFO
;
23 static bool arg_level_prefix
= true;
25 static int help(void) {
26 _cleanup_free_
char *link
= NULL
;
29 r
= terminal_urlify_man("systemd-cat", "1", &link
);
33 printf("%s [OPTIONS...] {COMMAND} ...\n\n"
34 "Execute process with stdout/stderr connected to the journal.\n\n"
35 " -h --help Show this help\n"
36 " --version Show package version\n"
37 " -t --identifier=STRING Set syslog identifier\n"
38 " -p --priority=PRIORITY Set priority value (0..7)\n"
39 " --level-prefix=BOOL Control whether level prefix shall be parsed\n"
40 "\nSee the %s for details.\n"
41 , program_invocation_short_name
48 static int parse_argv(int argc
, char *argv
[]) {
55 static const struct option options
[] = {
56 { "help", no_argument
, NULL
, 'h' },
57 { "version", no_argument
, NULL
, ARG_VERSION
},
58 { "identifier", required_argument
, NULL
, 't' },
59 { "priority", required_argument
, NULL
, 'p' },
60 { "level-prefix", required_argument
, NULL
, ARG_LEVEL_PREFIX
},
69 while ((c
= getopt_long(argc
, argv
, "+ht:p:", options
, NULL
)) >= 0)
82 arg_identifier
= NULL
;
84 arg_identifier
= optarg
;
88 arg_priority
= log_level_from_string(optarg
);
89 if (arg_priority
< 0) {
90 log_error("Failed to parse priority value.");
95 case ARG_LEVEL_PREFIX
: {
98 k
= parse_boolean(optarg
);
100 return log_error_errno(k
, "Failed to parse level prefix value.");
102 arg_level_prefix
= k
;
110 assert_not_reached("Unhandled option");
116 static int run(int argc
, char *argv
[]) {
117 _cleanup_close_
int fd
= -1, saved_stderr
= -1;
120 log_parse_environment();
123 r
= parse_argv(argc
, argv
);
127 fd
= sd_journal_stream_fd(arg_identifier
, arg_priority
, arg_level_prefix
);
129 return log_error_errno(fd
, "Failed to create stream fd: %m");
131 saved_stderr
= fcntl(STDERR_FILENO
, F_DUPFD_CLOEXEC
, 3);
133 r
= rearrange_stdio(STDIN_FILENO
, fd
, fd
); /* Invalidates fd on succcess + error! */
136 return log_error_errno(r
, "Failed to rearrange stdout/stderr: %m");
139 (void) execl("/bin/cat", "/bin/cat", NULL
);
141 (void) execvp(argv
[optind
], argv
+ optind
);
144 /* Let's try to restore a working stderr, so we can print the error message */
145 if (saved_stderr
>= 0)
146 (void) dup3(saved_stderr
, STDERR_FILENO
, 0);
148 return log_error_errno(r
, "Failed to execute process: %m");
151 DEFINE_MAIN_FUNCTION(run
);