(1) Unamed pipe
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
int main(char **argv, int agrc)
{
int pipe_fd[2];
pid_t pid;
char r_buf[100];
char w_buf[1000000 * 4];
char* p_wbuf;
int r_num;
int w_num;
int cmd;
memset(r_buf, 0, sizeof(r_buf));
memset(w_buf, 0, sizeof(w_buf));
p_wbuf=w_buf;
if( pipe(pipe_fd) < 0)
{
printf("pipe create error\n");
exit(-1);
}
if( (pid = fork()) == 0)
{
printf("\n");
close(pipe_fd[1]);
sleep(3);//确保父进程关闭写端
r_num=read(pipe_fd[0],r_buf,100);
printf("read num is %d the data read from the pipe is %d\n", r_num, atoi(r_buf));
close(pipe_fd[0]);
exit(0);
}
else if (pid > 0)
{
close(pipe_fd[0]);//read
memset(w_buf, 1, sizeof(w_buf));
if ( (w_num = write(pipe_fd[1], w_buf, 2000000)) != -1)
printf("parent write num:%d", w_num);
else
printf("parent write error");
close(pipe_fd[1]);//write
printf("parent close fd[1] over\n");
sleep(10);
exit(0);
}
}
(2) Named pipe (fifo)
Client:
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#define FIFO_SERVER "/tmp/fifoserver"
int main(int argc, char** argv)
{
int fd;
char r_buf[4096*2];
int r_size;
int real_rnum;
memset(r_buf, 0, 4096 * 2);
r_size = atoi(argv[1]);
printf("Request size:%d\n", r_size);
mode_t r_noblock = O_RDONLY | O_NONBLOCK;
mode_t r_block = O_RDONLY;
if( (fd = open(FIFO_SERVER, r_block, 0)) < 0)
{
if (errno == ENXIO)
{
printf("open error; no writing process\n");
exit(-1);
}
else
{
printf("open error\n");
exit(-1);
}
}
while (1)
{
memset(r_buf, 0, sizeof(r_buf));
real_rnum = read(fd, r_buf, r_size);
if (real_rnum == -1)
{
if (errno == EAGAIN)
printf("read to fifo error; try later\n");
}
else
printf("real read num is %d\n", real_rnum);
sleep(1);
}
pause();
unlink(FIFO_SERVER);
}
Server:
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#define FIFO_SERVER "/tmp/fifoserver"
int main(int argc,char** argv)
{
int fd;
char w_buf[4096*2];
int real_wnum;
memset(w_buf, 0, 4096*2);
if( (mkfifo(FIFO_SERVER, O_CREAT|O_EXCL) < 0) && (errno != EEXIST))
printf("cannot create fifoserver\n");
mode_t w_noblock = O_WRONLY|O_NONBLOCK;
mode_t w_block = O_WRONLY;
if( (fd = open(FIFO_SERVER, w_block, 0)) < 0)
{
if (errno == ENXIO)
printf("open error; no reading process\n");
else
printf("open error;\n");
}
real_wnum = write(fd, w_buf, 2048);
if (real_wnum == -1)
{
if (errno==EAGAIN)
printf("write to fifo error; try later\n");
}
else
printf("real write num is %d\n",real_wnum);
/*
real_wnum=write(fd,w_buf,5000);
real_wnum=write(fd,w_buf,4096);
*/
if (real_wnum == -1)
if (errno==EAGAIN)
printf("try later\n");
}