管道对于写入其中的数据A具有保护措施,当数据A没有读出的时候,再次向管道输送数据B ,此时数据B不会覆盖数据A,当读操作来临时,会把数据A和B按顺序读出。
#include <stdio.h>
#define CHILD_MESS "I am the first message/n"
#define PAR_MESS "I am the second message./n"
int main()
{
int pipefd[2];
int len;
char buf[BUFSIZ];
int read_len;
if(pipe(pipefd)==-1)
{
perror("fork");
exit(1);
}
if(write(pipefd[1],CHILD_MESS,strlen(CHILD_MESS))!=strlen(CHILD_MESS))
{
perror("writing to pipe");
exit(2);
}
if(write(pipefd[1],PAR_MESS,strlen(PAR_MESS))!=strlen(PAR_MESS))
{
perror("witing to pipe again befor the pre-one being read");
exit(3);
}
if((read_len=read(pipefd[0],buf,BUFSIZ))==-1)
{
perror("read pipe");
exit(4);
}
if(write(1,buf,read_len)!=read_len)
{
perror("write to stdout");
exit(5);
}
return 0;
}
输出结果:
[fxp@localhost ~]$ ./a.out
I am the first message
I am the second message.
#include <stdio.h>
#define CHILD_MESS "I am the first message/n"
#define PAR_MESS "I am the second message./n"
int main()
{
int pipefd[2];
int len;
char buf[BUFSIZ];
int read_len;
if(pipe(pipefd)==-1)
{
perror("fork");
exit(1);
}
if(write(pipefd[1],CHILD_MESS,strlen(CHILD_MESS))!=strlen(CHILD_MESS))
{
perror("writing to pipe");
exit(2);
}
if(write(pipefd[1],PAR_MESS,strlen(PAR_MESS))!=strlen(PAR_MESS))
{
perror("witing to pipe again befor the pre-one being read");
exit(3);
}
if((read_len=read(pipefd[0],buf,BUFSIZ))==-1)
{
perror("read pipe");
exit(4);
}
if(write(1,buf,read_len)!=read_len)
{
perror("write to stdout");
exit(5);
}
return 0;
}
输出结果:
[fxp@localhost ~]$ ./a.out
I am the first message
I am the second message.