管道客户服务端程序
来源:互联网 发布:前端软件有哪些? 编辑:程序博客网 时间:2024/05/05 02:44
管道包括无名管道和有名管道(FIFO),前者只能用于父进程和子进程之间的通信,后者可用于运行同一系统中的任意两个进程间通信。
注意:必须在系统调用fork()前调用pipe(),否则子进程将不会继承文件描述符(fd[0],fd[1]),否则,则是创建两个管道。
#include <unistd.h>#include <stdio.h>#include <strings.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <pthread.h>#include <sys/stat.h>#include <fcntl.h>#include <errno.h>void client(int,int);void server(int,int);#define MAXLINE 1024int main(int argc,char **argv){int pause=1;int pipe1[2],pipe2[2];pid_t childpid;pipe(pipe1);pipe(pipe2);if((childpid = fork()) == 0){close(pipe1[1]);close(pipe2[0]);server(pipe1[0],pipe2[1]);exit(0);} close(pipe1[0]);close(pipe2[1]);client(pipe2[0],pipe1[1]);waitpid(childpid,NULL,0);exit(0);}voidclient(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);}voidserver(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)//err_quit("end-of-file while reading pathname");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);}}
test.conf文件放在/ 目录下,内容如下://test.conftest ok!运行结果截图
- 管道客户服务端程序
- TCP客户、服务端程序示例
- 09_TCP客户服务端
- 多线程管道服务端
- 服务端程序
- 命名管道--简单的客户服务器通信
- C# Socket TCP 客户/服务端例子
- 采用select实现多客户服务端
- 黑马程序员_java基础客户-服务端模式
- Soket 服务端客户端接发消息
- web服务端向客户发送提示信息
- Qt客户服务端传输数据总结
- 并发客户服务程序
- 多客户网络程序
- 添加客户程序
- 测试用客户程序
- 管道调用程序
- 命名管道程序
- 去掉文件名中的路径
- 学校的论文答辩---问题准备
- gif图片拆帧及合成[python]实现
- ios5.1.1完美越狱
- 自动生成 Makefile 的全过程详解
- 管道客户服务端程序
- DropEdit
- x86中内存管理寄存器
- C# 快速入门
- 【RQNOJ2】【DP】【01背包】 开心的金明
- Create Managed Accounts in SharePoint
- POJ 1330 Nearest Common Ancestors [LCA+RMQ]
- poj 3648 Wedding+2-sat+SCC+缩点+拓扑排序
- [iOS] iPad与iPhone上各种标准控件的大小