Cool stuff: Pipeline library

如何在 C 程式中方便使用 pipeline 呢?

Unix pipeline 之父說 Unix 程式的哲學就是「只做一件事,並把它做好」:

“This is the Unix philosophy: Write programs that do one thing and do
it well. Write programs to work together. Write programs to handle
text streams, because that is a universal interface.”
― Doug McIlroy, the inventor of Unix pipes

平常有在使用 shell 的朋友想必對 | 這個符號不陌生,他可以把多個指令頭尾相接,各展所長,讓我們可以把各程式的力量組合起來成一個強大的 pipeline。

在 shell script 中可以輕鬆做到的事在程式中就不一定這麼簡單了,在 perl 中可以直接用 open 打開程式作為輸出入裝置,在 python 中有 subprocess 模組的 Popen 可以用,但如果只寫 C 呢?你可以用 pipe2 配合 forkexec—沒錯,想起 Unix Programming 課本了嗎 😉

用 C 寫這樣的程式既麻煩又容易寫錯,Colin Watson 寫到他在維護 man-db 的時候為此寫了專用的 pipeline library,現在決定要把 libpipeline 獨立以 GPLv3 釋出

使用 libpipeline 如果我們要產生像

    apt-get moo|cowsay -n

這樣的 pipeline,可以這樣寫:

    pipeline *p;
    int status;
    p = pipeline_new ();
    pipeline_command_args (p, "apt-get", "moo", NULL);
    pipeline_command_args (p, "cowsay", "-n", NULL);
    pipeline_start (p);
    status = pipeline_wait (p);
    pipeline_free (p);

還可以在 pipeline 中間安插 “built-in” 命令:

    command *inproc = command_new_function ("in-process", &func, NULL, NULL);
    pipeline_command (p, inproc);

有趣嗎?更詳細的說明可以參考 libpipeline(3) 說明文件。