频道栏目
首页 > 资讯 > 其他 > 正文

PIPE基础入门教学

18-08-01        来源:[db:作者]  
收藏   我要投稿

程序原运行后再输入一个文件名,程序打印文件内容:

main.c:
#include 
#include 
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include   /* Obtain O_* constant definitions */
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

void client(int,int),server(int,int);
#define MAXLINE  4096 /* max text line length */
#define FIFO_NAME "/tmp/mplayer.fifo"
int main(int argc,char *argv[]){

 int pipe1[2],pipe2[2],r,fd;
 pid_t childpid;
 int check_up=0;
 check_up=pipe(pipe1);
 assert(check_up>=0);
 check_up=pipe(pipe2);
 assert(check_up>=0);
 r = mkfifo(FIFO_NAME, 0755);
 if( -1 == r){
  assert(errno == EEXIST);
 }
 fd = open(FIFO_NAME, O_RDWR);
 assert(fd!=-1);

 struct stat buf;
 fstat(pipe1[0],&buf);
 if((check_up=S_ISFIFO(buf.st_mode))){//这里的返回值是1
  printf("check_up=%d,pipe1[0] is a fifo file\n",check_up);
 }else{
  printf("it is ...\n");
 }
 fstat(fd,&buf);
 if((check_up=S_ISFIFO(buf.st_mode))){//这里的返回值为什么也是1,有大佬能解释一下吗
//如果都一样怎么区分管道和FIFO
  printf("check_up=%d,fd is a fifo file\n",check_up);
 }else{
  printf("it is ...\n");
 }

 childpid=fork();
 assert(childpid>=0);
 if(childpid==0){
  close(pipe1[1]);//用1读
  close(pipe2[0]);//用2写

  server(pipe1[0],pipe2[1]);
  exit(0);
 }
 close(pipe1[0]);//用1写
 close(pipe2[1]);//用2读
 client(pipe2[0],pipe1[1]);
 exit(0);
}
void client(int readfd, int writefd)
{
 size_t  len;
 ssize_t n;
 char buff[MAXLINE];

  /* 4read pathname */
 fgets(buff, MAXLINE, stdin);
 len = strlen(buff);  /* fgets() guarantees null byte at end */
 if (buff[len-1] == '\n')
  len--;  /* delete newline from fgets() */

  /* 4write pathname to IPC channel */
 write(writefd, buff, len);

  /* 4read from IPC, write to standard output */
 while ( (n = read(readfd, buff, MAXLINE)) > 0)
  write(STDOUT_FILENO, buff, n);
}
void server(int readfd, int writefd)
{
 int  fd;
 ssize_t n;
 char buff[MAXLINE+1];

  /* 4read pathname from IPC channel */
 if ( (n = read(readfd, buff, MAXLINE)) == 0){
  printf("end-of-file while reading pathname");
  exit(0);
 }
 buff[n] = '\0';  /* null terminate pathname */

 if ( (fd = open(buff, O_RDONLY)) < 0) {
/* 4error: must tell client */
  snprintf(buff + n, sizeof(buff) - n, ": can't open, %s\n",
  strerror(errno));
  n = strlen(buff);
  write(writefd, buff, n);

 } else {
/* 4open succeeded: copy file to IPC channel */
  while ( (n = read(fd, buff, MAXLINE)) > 0)
write(writefd, buff, n);
  close(fd);
 }
}
相关TAG标签
上一篇:关于java中equals,hashcode和==的区别实例讲解
下一篇:创建项目并集成Swagger (框架实战)
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站