管道的局限性:
①数据不能进程自己写,自己读。
②管道中数据不可反复读取。-旦读走, 管道中不再存在。
③采用半双工通信方式,数据只能在单方向上流动。
④只能在有公共祖先的进程间使用管道
单通道将小写字母改为大写例程:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>int main(int argc,char *argv[])
{int ret;int fd[2];pid_t pid;char *str="abcdefg\n";char buf[100]="\0";ret = pipe(fd);if(-1 == ret){perror("pipe error");exit(1);}pid = fork();if(pid>0){//close(fd[0]);write(fd[1],str,strlen(str));close(fd[1]);//printf("parent %s\n",str);pid_t wpid = wait(NULL);ret = read(fd[0],buf,sizeof(buf));write(STDOUT_FILENO,buf,ret);close(fd[0]);printf("parent %s\n",buf);}else if(0 == pid){//close(fd[1]);ret = read(fd[0],buf,sizeof(buf));write(STDOUT_FILENO,buf,ret);close(fd[0]);int i;//int n = strlen(str);for(i=0;i<ret;i++){buf[i] =buf[i]-32;}//printf("child %s\n",str);write(fd[1],buf,strlen(buf));close(fd[1]);}else{perror("fork error");}return 0;
}
运行结果如图:
双通道将小写字母改为大写例程:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{int fd[2];int fd01[2];int ret,i,ret01;char *str="qwertyuiop\n";char buf[100]="\0";ret=pipe(fd);ret01=pipe(fd01);pid_t pid;pid=fork();if(ret == -1){perror("pipe error");}if(ret01 == -1){perror("pipe error");}else if(pid==-1){perror("fork error");}else if(pid == 0){close(fd[1]);ret=read(fd[0],buf,strlen(str));for(i=0;i<ret;i++){buf[i]=buf[i]-32;}close(fd01[0]);write(fd01[1],buf,ret);close(fd01[1]);close(fd[0]);printf("子进程里的东西:%s\n",str);exit(0);}else if(pid>0){close(fd[0]);write(fd[1],str,strlen(str));close(fd[1]);pid_t pid=wait(NULL);close(fd01[1]);read(fd01[0],buf,sizeof(buf));printf("父进程里的东西:%s\n",buf);exit(0);}
}
运行结果: