/*在这个例中,我们将在进程中新建一个管道,然后向它写入一个消息,管道读取消息后将其发出*/
#include
#include
#include
#define MAX_LINE 80
#define PIPE_STDIN 0
#define PIPE_STDOUT 1
/**
元素myPipe[1]包含的文件描述符用于管道的输入
元素myPipe[0] 包含的文件描述符用于管道的输出
----mypipe[1] -----mypipe[0]
write() -|---------------->mypipe----------------->read()
----stdout -----stdin
*/
int main()
{
const char *string={"A sample message."};
int ret, myPipe[2];
char buffer[MAX_LINE+1];
/* 建立管道 */
ret = pipe( myPipe );
if (ret == 0) {
/* 将消息写入管道 */
//用write函数把消息写入管道。站在应用程序的角度,它是在向stdout输出
write( myPipe[PIPE_STDOUT], string, strlen(string) );
/* 从管道读取消息 */
ret = read(myPipe[PIPE_STDIN], buffer, MAX_LINE);
/* 利用NULL结束字符串 */
//buffer变量的末尾添加一个NULL,这样就能利用printf函数正确的输出它了
buffer[ ret ] = 0;
printf("%s\n", buffer);
}
return 0;
}
/*演示两个进程间的管道模型的代码*/
#include
#include
#include
#include
#define MAX_LINE 80
int main()
{
int thePipe[2], ret;
char buf[MAX_LINE+1];
const char *testbuf={"a test string."};
if ( pipe( thePipe ) == 0 )
{
if (fork() == 0)
{
ret = read( thePipe[0], buf, MAX_LINE );
buf[ret] = 0;
printf( "Child read %s\n", buf );
}
else
{
ret = write( thePipe[1], testbuf, strlen(testbuf) );
ret = wait( NULL );
}
close( thePipe[0] );
close( thePipe[1] );
}
return 0;
}
fifo_read.c
/*fifo_read.c*/
#include
#include
#include
#include
#include
#include
#include
#include
/*定义FIFO路径*/
#define FIFO "/tmp/myfifo"
int main(int argc,char** argv)
{
char buf_r[100];
int fd;
int nread;
/*创建FIFO管道*/
if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))
printf("cannot create fifoserver\n");
printf("Preparing for reading bytes...\n");
memset(buf_r,0,sizeof(buf_r));
/*打开FIFO管道,不阻塞方式*/
fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);
if(fd==-1)
{
perror("open");
exit(1);
}
while(1)
{
memset(buf_r,0,sizeof(buf_r));
/*读管道,因为定义了非阻塞方式,故在此不会阻塞进程*/
if((nread=read(fd,buf_r,100))==-1){
if(errno==EAGAIN) printf("no data yet\n");
}
printf("read %s from FIFO\n",buf_r);
sleep(1);
}
pause();
unlink(FIFO);
return 0;
}
fifo_write.c
/*fifo_write.c*/
#include
#include
#include
#include
#include
#include
#include
#include
/*FIFO管道路径*/
#define FIFO_SERVER "/tmp/myfifo"
int main(int argc,char** argv)
{
int fd = 0;
char w_buf[100];
int nwrite;
/*打开FIFO管道*/
fd=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);
if(fd==-1);
if(errno == ENXIO)
printf("open error; no reading process\n");
/*判断有没有参数输入*/
if(argc==1)
printf("Please send something\n");
/*复制参数输入*/
strcpy(w_buf,argv[1]);
/*写到FIFO去*/
if((nwrite=write(fd,w_buf,100))==-1) {
if(errno==EAGAIN)
printf("The FIFO has not been read yet.Please try later\n");
}
else
/*输出写入的内容*/
printf("write %s to the FIFO\n",w_buf);
return 0;
}