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.

typedef for function pointer


#include <stdio.h>
typedef void (*VPF) (int *, int *);
void Square(int *rX, int *rY);
void Swap(int *rX, int *rY);
void PrintVals(VPF,int , int );

int main()
{
int valOne=2, valTwo=5;
VPF pFunc;

pFunc = Swap;
PrintVals ( pFunc, valOne, valTwo);

pFunc = Square;
PrintVals ( pFunc, valOne, valTwo);

return 0;
}

void PrintVals( VPF pFunc,int x, int y)
{
printf("x:%d y:%d\n",x,y);
pFunc(&x,&y);
printf("x:%d y:%d\n",x,y);
printf("\n");
}

void Square(int *rX, int *rY)
{
(*rX) *= (*rX);
(*rY) *= (*rY);
}

void Swap(int *rX, int *rY)
{
int temp;
temp = *rX;
*rX = *rY;
*rY = temp;
}


執行結果:

x:2 y:5
x:5 y:2

x:2 y:5
x:4 y:25