linux进程通信(三)--FIFO

wpeng 2009-12-16

1./*fifoserver.c:向FIFO中写入信息*/

2.#include<sys/types.h>

3.#include<sys/stat.h>

4.#include<errno.h>

5.#include<fcntl.h>

6.#defineFIFO_SERVER"FIFO4"

7.main(intargc,char**argv)

8.{

9.intfd=0;

10.charw_buf[4096];

11.intreal_wnum;

12.memset(w_buf,0,4096);

13.if((mkfifo(FIFO_SERVER,O_CREAT|O_EXCL|0666)<0)&&(errno!=EEXIST))

14.printf("cannotcreatefifoserver\n");

15./*此处存在着打开依赖,即若没有读端打开FIFO的话,写端就阻塞在写端*/

16.fd=open(FIFO_SERVER,O_WRONLY);

17.if(fd==-1)

18.printf("openerror;noreadingprocess\n");

19.printf("%d\n",fd);

20.

21.real_wnum=write(fd,w_buf,2048);

22.if(real_wnum==-1)

23.printf("writetofifoerror;trylater\n");

24.else

25.printf("realwritenumis%d\n",real_wnum);

26./*往FIFO写入的数据都是原子的,如果没有足够的空间,则会等待,而不是一点一点的写入。*/

27.real_wnum=write(fd,w_buf,4096);

28.if(real_wnum==-1)

29.printf("writetofifoerror;trylater\n");

30.else

31.printf("realwritenumis%d\n",real_wnum);

32.}

1./*fifoclient.c:从FIFO中读出数据*/

2.#include<sys/types.h>

3.#include<sys/stat.h>

4.#include<errno.h>

5.#include<fcntl.h>

6.#defineFIFO_SERVER"FIFO4"

7.main(intargc,char**argv)

8.{

9.charr_buf[4096];

10.intfd;

11.intr_size;

12.intret_size;

13.r_size=atoi(argv[1]);

14.memset(r_buf,0,sizeof(r_buf));

15.fd=open(FIFO_SERVER,O_RDONLY);

16.if(fd==-1)

17.{

18.printf("open%sforreaderror\n");

19.exit(1);

20.}

21.printf("%d\n",fd);

22.

23.while(1)

24.{

25.ret_size=read(fd,r_buf,r_size);

26.if(ret_size==-1)

27.printf("nodataavlaible\n");

28.else

29.printf("realreadbytes%d\n",ret_size);

30.sleep(1);

31.}

32.unlink(FIFO_SERVER);

  33. } 

相关推荐