1、管道( pipe ):管道是一种半双工的通信方式,数据只能单向流动,而且只能在具有亲缘关系的进程间使用。进程的亲缘关系通常是指父子进程关系。
2、有名管道 (named pipe) : 有名管道也是半双工的通信方式,但是它允许无亲缘关系进程间的通信。
这个例子是,父进程创建子进程,父进程向子进程通过管道发送一个字符串,子进程读取该字符串显示并倒序后发送到父进程,父进程读取该倒序后的字符串并打印出来。
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
char sendbuf[] = "This is a pipe test!";
char recbuf[22];
char parrecbuf[22];
void reverse(char *str1){/*字符倒序函数*/
if (str1 == NULL) return;
char *p = str1;
char *q = str1;
while (*q) ++q;
q--;
while(q > p){
char t = *p;
*p++ = *q;
*q-- = t;
}
}
int main() {
int mypipe[2],fd;
if ( pipe(mypipe) < 0) { perror("pipe faild"); exit(0); }
if ( (fd=fork()) < 0) { perror("fork faild"); exit(0); }
if (fd == 0) {
read (mypipe[0],recbuf,strlen(sendbuf));
printf("The child process get: %s\n",recbuf );
reverse(recbuf);//倒序字符
write(mypipe[1],recbuf,strlen(recbuf));//向管道内写入倒序后的字符串
}
if (fd > 0) {
write(mypipe[1],sendbuf,strlen(sendbuf));
sleep(10);//等待子进程从管道将数据取走
read(mypipe[0],parrecbuf,strlen(sendbuf));
printf("The parent process get: %s\n",parrecbuf );
wait();//防止僵尸进程
}
}