管道简单介绍:

管道是单向的、先进先出的、无结构的、固定大小的字节流,它把一个进程的标准输出和还有一个进程的标准输入连接在一起。

写进程在管道的尾端写入数据。读进程在管道的首端读出数据。数据读出后将从管道中移走。其他读进程都不能再读到这些数据。管道提供了简单的流控制机制。进程试图读空管道时。在有数据写入管道前,进程将一直堵塞。相同,管道已经满时,进程再试图写管道,在其他进程从管道中移走数据之前,写进程将一直堵塞。


关于管道的代码实例

此程序是关于管道的创建和读写和关闭
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>

int main(void)
{
int fd[2];
char str[256];

if( pipe(fd) < 0 )
{
perror("pipe");
exit(1);
}

write(fd[1],"create the pipe successfully!\n ",31);

read(fd[0],str,sizeof(str));
printf("%s",str);

printf("pipe file descriptors are %d ,%d\n",fd[0],fd[1]);

close(fd[0]);
close(fd[1]);
return 0;
}
此程序说明管道内的数据在读出之后就没有了
#include<stdio.h>
#include<unistd.h>
int main()
{
int filedes[2];
char buffer[20];

pipe(filedes);
if( fork()> 0)
{
char s[]="hello\n";
write(filedes[1],s,sizeof(s));
}
else
{
read(filedes[0],buffer,80);
printf("%s\n",buffer);
}

read(filedes[0],buffer,80);
printf("%s\n",buffer);
close(filedes[0]);
close(filedes[1]);

return 0;
}


父子进程之间的通过管道进行通信
#include<unistd.h>
#include<stdio.h>
#include<fcntl.h>
#include<sys/types.h>


int main()
{
int fd[2];
char buf[20];
pid_t pid;
int len;

if( pipe(fd) < 0 )
{
perror("failed to pipe;");
return 1;
}

if( ( pid = fork() ) < 0 )
{
perror("failed to fork;");
return 1;
}
else if( pid > 0 )
{
close(fd[0]);
write(fd[1],"hello my son\n",14);
return 0;
}
else
{
close(fd[1]);
read(fd[0],buf,20);
printf("%s\n",buf);
}
return 0;
}


兄弟进程之间进行通信
要点:须要在第二次创建一个子进程的时候关闭父进程管道的两端,
而不是第一次,这样做的目的是继承一个存活的管道。
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/types.h>

int main( void )
{
int fd[2];
char buf[100];
pid_t pid;
int len;

if( pipe(fd) < 0 )
perror("pipe");

if( ( pid = fork() ) < 0)
perror("fork1");
else if( pid == 0 )
{
close(fd[0]);
write(fd[1],"hello brother!",20);
exit(0);
}

if( ( pid = fork() ) < 0)
perror("fork2");
else if( ( pid > 0 ) < 0)
{
close(fd[0]);
close(fd[1]);
exit(0);
}
else
{
close(fd[1]);
read(fd[0],buf,20);
printf("%s\n",buf);
}
return 0;
}