2009年4月29日 星期三

FIFO: communication between two process

為了控制另一個程式的執行,這個範例用了pipe的方式,兩個程式之間用pipe來溝通(不過是單向),利用這種方式,我們就可以很簡單的控制另一個程式的執行。

r.c: read date.
w.c: write data.

r.c

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>

#define FIFO_NAME "/tmp/my_fifo"
#define BUFFER_SIZE PIPE_BUF

int main(int argc, char *argv[])
{
int res;
int open_mode = 0;
int n=0;
char MYkey;
open_mode= O_RDONLY | O_NONBLOCK; //是nonblock的

if (access(FIFO_NAME, F_OK) == -1) {
res = mkfifo(FIFO_NAME, 0777);
if (res != 0) {
fprintf(stderr, "Could not create fifo %s\n", FIFO_NAME);
exit(EXIT_FAILURE);
}
}

res = open(FIFO_NAME, open_mode);
while(1)
{
n=read(res,&MYkey,BUFFER_SIZE);
if(n>0)
printf("%c\n",MYkey);
else
printf("No Data.\n");
sleep(1);
}
exit(EXIT_SUCCESS);
}



w.c

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>

#define FIFO_NAME "/tmp/my_fifo"
#define BUFFER_SIZE PIPE_BUF

int main(int argc, char *argv[])
{
int res;
int open_mode = 0;
int n=0;
char MYkey='A';
open_mode= O_WRONLY | O_NONBLOCK;

if (access(FIFO_NAME, F_OK) == -1) {
res = mkfifo(FIFO_NAME, 0777);
if (res != 0) {
fprintf(stderr, "Could not create fifo %s\n", FIFO_NAME);
exit(EXIT_FAILURE);
}
}

res = open(FIFO_NAME, open_mode);
while(1)
{
n=write(res,&MYkey,BUFFER_SIZE);
if(n>0)
printf("write %c\n",MYkey);
sleep(3);
MYkey++;
}
exit(EXIT_SUCCESS);
}



執行結果:

[root@ecken02 fifo]# ./r &
[1] 16226
No Data.
[root@ecken02 fifo]# ./w
write A
A
No Data.
No Data.
write B
B
No Data.
No Data.
write C
C
No Data.

沒有留言: