Linux进程通信方法--管道
2010-07-28 16:30
501 查看
1 pipe
#include <unistd.h>
int pipe(int filedes[2]);
只能用以父子进程之间进行通信。注意,pfd[0]只能read,pfd[1]只能write.是一个单向的。
2 fifo 即命名管道
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
mkfifo() 用法和creat用法相同,创建出一个虚拟的文件,可以在没有关系的进程之间进行共享,传递信息。创建好之后就可以像对待一个文件一样使用它。
注意在非阻塞模式下,write only的打开会直到有read only的open发生时,才会返回。反之read only的open直到write only的open发生时才会返回。在阻塞模式下,read only的open会立刻返回,但是write only的open,在没有为读而打开的情况下会返回1,errno会被置为ENXIO。
示例:
//先执行的进程
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
int fd = 0;
if(mkfifo("fifo.tmp",S_IRUSR | S_IWUSR) < 0)
perror("mkfifo failed!");
if((fd = open("fifo.tmp",O_WRONLY)) <= 0 )
perror("error open fifo");
if(write(fd,"hello",6) != 6)
perror("error write");
close(fd);
return 0;
}
//后执行的进程
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
int fd = 0;
char buf[32];
if((fd = open("fifo.tmp",O_RDONLY)) <= 0 )
perror("error open fifo");
if(read(fd,buf,sizeof(buf)) <= 0)
perror("error read");
printf("read %s/n",buf);
close(fd);
return 0;
}
第一个程序先运行会阻塞,直到第二个程序运行。
#include <unistd.h>
int pipe(int filedes[2]);
只能用以父子进程之间进行通信。注意,pfd[0]只能read,pfd[1]只能write.是一个单向的。
2 fifo 即命名管道
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
mkfifo() 用法和creat用法相同,创建出一个虚拟的文件,可以在没有关系的进程之间进行共享,传递信息。创建好之后就可以像对待一个文件一样使用它。
注意在非阻塞模式下,write only的打开会直到有read only的open发生时,才会返回。反之read only的open直到write only的open发生时才会返回。在阻塞模式下,read only的open会立刻返回,但是write only的open,在没有为读而打开的情况下会返回1,errno会被置为ENXIO。
示例:
//先执行的进程
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
int fd = 0;
if(mkfifo("fifo.tmp",S_IRUSR | S_IWUSR) < 0)
perror("mkfifo failed!");
if((fd = open("fifo.tmp",O_WRONLY)) <= 0 )
perror("error open fifo");
if(write(fd,"hello",6) != 6)
perror("error write");
close(fd);
return 0;
}
//后执行的进程
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
int fd = 0;
char buf[32];
if((fd = open("fifo.tmp",O_RDONLY)) <= 0 )
perror("error open fifo");
if(read(fd,buf,sizeof(buf)) <= 0)
perror("error read");
printf("read %s/n",buf);
close(fd);
return 0;
}
第一个程序先运行会阻塞,直到第二个程序运行。
相关文章推荐
- linux进程通信-有名管道
- linux中利用有名管道实现进程之间的通信
- linux先进程通信 管道方式和消息队列
- linux中,管道能够在同一进程中进行通信吗?
- 简单解析linux下进程通信方法
- Linux下进程通信的八种方法
- Linux编程实践----进程间的通信IPC--管道
- linux 命名管道fifo实现进程间小数据通信
- Linux间进程通信-----之使用命名管道
- Linux进程通信之管道(匿名,命名)
- LINUX编程——进程间管道通信
- 服务器serverbuffergcc数据结构Linux进程通信:命名管道FIFO小结
- linux进程无名管道通信
- Linux下进程的通信方式: 有名管道(命名管道)
- Linux(八):进程通信IPC(二)之命名管道
- Linux进程通信:命名管道FIFO小结
- Linux进程通信:管道
- Linux进程通信之管道
- Linux 进程通信之管道
- linux基础编程:进程通信之管道