93 lines
2.0 KiB
C
93 lines
2.0 KiB
C
#include <stdio.h>
|
|
#include <unistd.h>
|
|
#include <fcntl.h>
|
|
#include <sys/types.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/wait.h>
|
|
#include <errno.h>
|
|
#include <string.h>
|
|
|
|
// 单机聊天工具 (bob方)
|
|
int main(int argc, char const *argv[])
|
|
{
|
|
// 使用方法 gcc xx.c -D CREATE_FIFO 会在运行时执行预处理区段
|
|
#ifdef CREATE_FIFO
|
|
mkfifo("fifo_bob_to_lucy", 0644);
|
|
mkfifo("fifo_lucy_to_bob", 0644);
|
|
#endif
|
|
|
|
if (mkfifo("fifo_bob_to_lucy", 0644) != -1)
|
|
{
|
|
if (errno != EEXIST)
|
|
{
|
|
perror("fifo_bob_to_lucy");
|
|
return 1;
|
|
}
|
|
}
|
|
if (mkfifo("fifo_lucy_to_bob", 0644) != -1)
|
|
{
|
|
if (errno != EEXIST)
|
|
{
|
|
perror("fifo_lucy_to_bob");
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
int i = 0;
|
|
for (; i < 2; i++)
|
|
{
|
|
int pid = fork();
|
|
if (pid == 0)
|
|
break;
|
|
}
|
|
if (i == 0)
|
|
{
|
|
// 第一个子进程
|
|
// 从键盘输入数据并发送给对方 (bob -> lucy)
|
|
int fd = open("fifo_bob_to_lucy", O_WRONLY); // 只写消息
|
|
while (1)
|
|
{
|
|
char buf[128] = {};
|
|
int len = read(STDIN_FILENO, buf, 128);
|
|
buf[len - 1] = '\0';
|
|
write(fd, buf, len);
|
|
if (strcmp(buf, "bye") == 0)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
close(fd);
|
|
_exit(0);
|
|
}
|
|
else if (i == 1)
|
|
{
|
|
// 第二个进程,读数据 (lucy -> bob)
|
|
int fd = open("fifo_lucy_to_bob", O_RDONLY);
|
|
while (1)
|
|
{
|
|
char buf[128] = "";
|
|
int len = read(fd, buf, 128);
|
|
if (len <= 0)
|
|
break;
|
|
printf("接收 Lucy: %s\n", buf);
|
|
}
|
|
close(fd);
|
|
_exit(0);
|
|
}
|
|
else
|
|
{
|
|
// 主进程
|
|
while (1)
|
|
{
|
|
// int status;
|
|
int pid_ = waitpid(0, NULL, WNOHANG);
|
|
if (pid_ == -1)
|
|
{
|
|
// 所有子进程都已经退出
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return 0;
|
|
}
|