参考自:
程序间通信可以使用命名管道FIFO,在硬盘中建立管道文件。具体实例如下:
/** *gcc -g -o fifo_w fifo_w.c `pkg-config gtk+-2.0 --cflags --libs gthread-2.0` * */ #define _POSIX_SOURCE #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> main() { char fn[]="/tmp/temp.fifo"; char out[20]="FIFO's are fun!"; int wfd; if (mkfifo(fn, S_IRWXU) != 0) perror("mkfifo() error"); else { if ((wfd = open(fn, O_WRONLY)) < 0) perror("open() error for write end"); else { if (write(wfd, out, strlen(out)+1) == -1) perror("write() error"); close(wfd); } } unlink(fn); }
/** *gcc -g -o fifo_r fifo_r.c `pkg-config gtk+-2.0 --cflags --libs gthread-2.0` * */ #define _POSIX_SOURCE #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> main() { char fn[]="/tmp/temp.fifo"; char in[20]; int rfd; if ((rfd = open(fn, O_RDONLY|O_NONBLOCK)) < 0) perror("open() error for read end"); else { if (read(rfd, in, sizeof(in)) == -1) perror("read() error"); else printf("read '%s' from the FIFO\n", in); } close(rfd); }
运行结果:
terminal1:
[socol@localhost gtk]$ ./fifo_w
terminal2:
[socol@localhost gtk]$ ./fifo_r
read 'FIFO's are fun!' from the FIFO