管道客户服务端程序

管道包括无名管道和有名管道(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 1024
int 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);
}

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)
//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.conf
test ok!


运行结果截图













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值