#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
const int SIZE=128;
//gcc a.c -o a
//./a 用户名 写管道名 读管道名
int main(int argc, char **argv) {
if(argc != 4)
{
printf("参数错误!");
exit(1);
}
char *name = argv[1],
*write_pipe = argv[2],
*read_pipe = argv[3];
//子进程写
if(0 == fork())
{
char buf[SIZE];
int write_fd = -1;
// 创建写管道
if(-1 == access(write_pipe, F_OK))
if(-1 == (write_fd = mkfifo(write_pipe,0644)))
perror("mkfifo");
//打开写管道
if(-1 == (write_fd = open(write_pipe, O_WRONLY)))
perror("open");
while(1)
{
memset(buf, 0, SIZE);
fgets(buf, SIZE, stdin);
write(write_fd, name, strlen(name));
write(write_fd, ":", 1);
write(write_fd, buf, SIZE);
}
exit(0);
}
//父进程读
char buf[SIZE];
int read_fd = -1;
// //创建读管道
if(-1 == access(read_pipe, F_OK))
if(-1 == (read_fd = mkfifo(read_pipe,0644)))
perror("mkfifo");
//打开读管道
if(-1 == (read_fd = open(read_pipe, O_RDONLY)))
perror("open");
while(1)
{
memset(buf, 0, SIZE);
if(read(read_fd, buf, SIZE) <= 0)
{
perror("read");
break;
}
printf("\n%s",buf);
}
return 0;
}