一直没有时间系统的学习进程间通讯,这几天买了一本Stevens的UNIX网络编程两卷,决定开始认真学习下进程间通讯,
先从基本的管道pipe开始,代码如下:
#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
using namespace std;
const int MAXLINE = 1024;
/*
*
*/
void server(int,int);
void client(int,int);
int main(int argc, char** argv) {
int pipe1[2],pipe2[2];
pid_t child_pid;
pipe(pipe1);
pipe(pipe2);
if( (child_pid = 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(child_pid,NULL,0);
exit(0);
}
void client(int readfd,int writefd)
{
size_t len;
ssize_t n;
char buff[MAXLINE];
fgets(buff,MAXLINE,stdin);
len = strlen(buff);
if(buff[len-1]=='\n')
--len;
write(writefd,buff,len);
while( (n=read(readfd,buff,MAXLINE))>0 )
{
buff[n] = '\0';
write(STDOUT_FILENO, buff, n+1);
}
}