Skip to content

Instantly share code, notes, and snippets.

@furandon-pig
Created November 28, 2021 18:32
Show Gist options
  • Save furandon-pig/3d226a9b8faca9261726fce0ddad3633 to your computer and use it in GitHub Desktop.
Save furandon-pig/3d226a9b8faca9261726fce0ddad3633 to your computer and use it in GitHub Desktop.
LibXoを使用してpsコマンドの出力をJSON/XMLで行うサンプルプログラムです。
#include <libxo/xo.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
char buf[BUFSIZ];
char *c = NULL;
char *pid;
char *terminal_name;
char *state;
char *cpu_time;
char *command;
#if 0
typedef struct xo_info_s {
const char *xi_name; /* Name of the element */
const char *xi_type; /* Type of field */
const char *xi_help; /* Description of field */
} xo_info_t;
#endif
xo_info_t info[] = {
{ "pid", "number", NULL },
{ "terminal-name", "string", NULL },
{ "state", "string", NULL },
{ "cpu-time", "string", NULL },
{ "command", "string", NULL },
{ NULL, NULL, NULL }
};
int info_count = (sizeof(info) / sizeof(info[0])) - 1;
argc = xo_parse_args(argc, argv);
if (argc < 0) {
exit(EXIT_FAILURE);
}
xo_set_info(NULL, info, info_count);
xo_open_container_h(NULL, "process-information");
xo_open_list("process");
int count = 0;
FILE *io = popen("ps ax", "r");
if (io) {
while (fgets(buf, BUFSIZ-1, io)) {
// "ps ax"コマンドの以下の出力をパースする。
// PID TTY STAT TIME COMMAND
// 0 ? DKl 3:12.73 [system]
// 1 ? Is 0:00.02 init
// ...
if (count++ == 0) continue; // 先頭行は見出しなのでスキップする。
c = strchr(buf, '\n'); // 改行を取り除く
if (c) *c = '\0';
c = buf; // 改めて読み込んだ文字列の先頭から処理する。
while (*c++ == ' '); // プロセスID
pid = --c;
c = strchr(c, ' '); *c++ = '\0'; while (*c == ' ') { c++; }
while (*c++ == ' '); // tty名
terminal_name = --c;
c = strchr(c, ' '); *c++ = '\0'; while (*c == ' ') { c++; }
while (*c++ == ' '); // プロセスの状態
state = --c;
c = strchr(c, ' '); *c++ = '\0'; while (*c == ' ') { c++; }
while (*c++ == ' '); // CPU時間
cpu_time = --c;
c = strchr(c, ' '); *c++ = '\0'; while (*c == ' ') { c++; }
while (*c++ == ' '); // コマンド文字列
command = --c;
xo_open_instance("process");
xo_emit("{L:pid} '{:pid/%s}':\n", pid);
xo_emit("{L:terminal-name} '{:terminal-name/%s}':\n", terminal_name);
xo_emit("{L:state} '{:state/%s}':\n", state);
xo_emit("{L:cpu-time} '{:cpu-time/%s}':\n", cpu_time);
xo_emit("{L:command} '{:command/%s}':\n", command);
xo_close_instance("process");
}
pclose(io);
}
xo_close_list("process");
xo_close_container_h(NULL, "process-information");
xo_finish();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment