日期:2014-05-16 浏览次数:20852 次
Linux下多任务间通信-管道
嵌入式开发交流群280352802,欢迎加入!
管道式Linux系统中最古老的进程间通信机制,这里所说的管道是指无名管道(PIPE),它可用于具有亲缘关系进程间的通信.有名管道(FIFO)克服了管道没有名字的限制,因此,除了具有管道所有具有的功能外,它还允许无亲缘关系进程间的通信.Linux的管道主要包括两种:无名管道和有名管道,本文主要介绍这两种管道.
把一个进程连接到另一个进程的一个数据流称为"管道".比如:ls|more.这条命令的作用是列出当前目录下的所有文件盒子目录,如果内容超过了一页则自动进行分页.符号"|"就是shell为ls和more命令简历的一条管道,它将ls的输出直接送进了more的输入.
无名管道特点#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
static const char mesg[] = "Hello world!";
char buf[BUFSIZ];
ssize_t rcount, wcount;
int pipefd[2];
size_t len;
/*创建管道*/
if (pipe(pipefd) < 0) {
fprintf(stderr, "%s: pipe failed: %s\n", argv[0],
strerror(errno));
exit(1);
}
printf("PIPE: Read end = fd %d, write end = fd %d\n",
pipefd[0], pipefd[1]);
/*写管道*/
len = strlen(mesg);
if ((wcount = write(pipefd[1], mesg, len)) != len) {
fprintf(stderr, "%s: write failed: %s\n", argv[0],
strerror(errno));
exit(1);
}
printf("Write <%s> via pipe\n", mesg);
/*读管道*/
if ((rcount = read(pipefd[0], buf, BUFSIZ)) != wcount) {
fprintf(stderr, "%s: read failed: %s\n", argv[0],
strerror(errno));
exit(1);
}
buf[rcount] = '\0';
/*添加字符串终止字符*/
printf("Read <%s> from pipe\n", buf);
/*关闭管道*/
close(pipefd[0]);
close(pipefd[1]);
return 0;
}