作者:黃浩文
在 UNIX 核心環境裡,首要課題之一就是如何處理不同行程之間的通訊與資料交換。本文從最簡單的管道出發,示範同一台機器上的行程如何被建立、控制與溝通。
常見的 IPC 方式包括:Pipes、Signals、Message Queues、Semaphores、Shared Memory 與 Sockets。本文聚焦 Pipe,其餘留待後續討論。
UNIX 下開啟管道有兩種途徑:格式化管道(Formatted Piping)與低階管道(Low Level Piping)。
FILE *popen(char *command, char *type);
command 描述要建立的行程,type 描述開啟方式:「r」為讀、「w」為寫。回傳值是一個指標流,出錯時為 NULL。
用 popen() 開啟的管道,用完必須以 pclose(FILE *stream) 關閉;與管道溝通則透過 fprintf() 與 fscanf()。
int pipe(int fd[2]);
它會建立一個管道與兩個檔案描述子:fd[0] 用於讀、fd[1] 用於寫。成功回傳 0,失敗回傳 -1 並將原因寫入 errno。
標準編程模式:
fork() 建立父子(或多個)相關行程;read()/write() 操作管道;close(int fd) 關閉。以下片段示範父行程向子行程寫入資料:
int pdes[2];
pipe(pdes);
if (fork() == 0) { /* child */
close(pdes[1]); /* 不需要寫端 */
read(pdes[0], ...); /* 讀父行程來的資料 */
} else {
close(pdes[0]); /* 不需要讀端 */
write(pdes[1], ...); /* 寫給子行程 */
}
本實例由 plot.c(主程式)與 plotter.c 兩個模組組成,執行環境為 Solaris 2.6,需預先安裝 GNU 的 gnuplot 於 /usr/local/bin/。plot.c 呼叫 gnuplot,產生兩組資料流:y = sin(x) 與 y = sin(1/x),並為每組資料流各開一個管道。程式已在 Solaris 2.6 環境下除錯通過。
/* plot.c - example of unix pipe.
* Calls gnuplot to draw graphs from within a C program.
* Creates 2 pipes: one draws y=0.5 and y=random 0-1.0,
* the other draws y=sin(1/x) and y=sin x.
* compile: cc -o plot plot.c plotter.c
*/
#include "externals.h"
#include <stdio.h>
#define DEG_TO_RAD(x) (x*180/M_PI)
double drand48();
void quit();
FILE *fp1, *fp2, *fp3, *fp4, *fopen();
main() {
float i;
float y1, y2, y3, y4;
if (((fp1 = fopen("plot11.dat","w")) == NULL) ||
((fp2 = fopen("plot12.dat","w")) == NULL) ||
((fp3 = fopen("plot21.dat","w")) == NULL) ||
((fp4 = fopen("plot22.dat","w")) == NULL)) {
printf("Error can't open one or more data files\n");
exit(1);
}
signal(SIGINT, quit); /* trap ctrl-c */
StartPlot();
y1 = 0.5;
srand48(1);
for (i = 0; ; i += 0.01) {
y2 = (float) drand48();
if (i == 0.0) y3 = 0.0;
else y3 = sin(DEG_TO_RAD(1.0 / i));
y4 = sin(DEG_TO_RAD(i));
fprintf(fp1, "%f %f\n", i, y1);
fprintf(fp2, "%f %f\n", i, y2);
fprintf(fp3, "%f %f\n", i, y3);
fprintf(fp4, "%f %f\n", i, y4);
fflush(fp1); fflush(fp2); fflush(fp3); fflush(fp4);
PlotOne();
usleep(250);
}
}
void quit() {
printf("\nctrl-c caught:\n Shutting down pipes\n");
StopPlot();
printf("closing data files\n");
fclose(fp1); fclose(fp2); fclose(fp3); fclose(fp4);
printf("deleting data files\n");
RemoveDat();
}
/* plotter.c module */
#include "externals.h"
static FILE *plot1, *plot2, *ashell;
static char *startplot1 = "plot [] [0:1.1]'plot11.dat' with lines, 'plot12.dat' with lines\n";
static char *startplot2 = "plot 'plot21.dat' with lines, 'plot22.dat' with lines\n";
static char *replot = "replot\n";
static char *command1 = "/usr/local/bin/gnuplot> dump1";
static char *command2 = "/usr/local/bin/gnuplot> dump2";
static char *deletefiles = "rm plot11.dat plot12.dat plot21.dat plot22.dat";
static char *set_term = "set terminal x11\n";
void StartPlot(void) {
plot1 = popen(command1, "w");
fprintf(plot1, "%s", set_term); fflush(plot1);
if (plot1 == NULL) exit(2);
plot2 = popen(command2, "w");
fprintf(plot2, "%s", set_term); fflush(plot2);
if (plot2 == NULL) exit(2);
}
void RemoveDat(void) {
ashell = popen(deletefiles, "w");
exit(0);
}
void StopPlot(void) { pclose(plot1); pclose(plot2); }
void PlotOne(void) {
fprintf(plot1, "%s", startplot1); fflush(plot1);
fprintf(plot2, "%s", startplot2); fflush(plot2);
}
void RePlot(void) {
fprintf(plot1, "%s", replot); fflush(plot1);
}
#ifndef EXTERNALS #define EXTERNALS #include <stdio.h> #include <stdlib.h> #include <math.h> void StartPlot(void); void RemoveDat(void); void StopPlot(void); void PlotOne(void); void RePlot(void); #endif
這個例子說明了管道最典型的使用情境:主程式把資料寫進管道,另一支程式(gnuplot)從另一端讀取並即時作圖。注意每次寫入後都要 fflush(),否則緩衝區未清空,讀取端就看不到新資料。
作者信箱:vong@21cn.com