#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
char str[1024] = {""};
int main(int argc, char const *argv[])
{
int fd = open("my.txt", O_RDWR | O_CREAT | O_TRUNC, 0777);
int fd1 = open("my1.txt", O_RDWR | O_CREAT | O_TRUNC, 0777);
if (fd == -1)
{
perror("");
}
//产生一个进程
pid_t pid = fork();
if (pid > 0) //父进程发送数据
{
while (1)
{
printf("请输入想要跟儿子说的话:\n");
scanf("%s", str);
lseek(fd, 0, SEEK_SET);
ssize_t f1 = write(fd, str, strlen(str));
if (f1 < 0)
{
printf("写入失败\n");
}
}
}
if (pid == 0) // 子进程接收数据
{
while (1)
{
lseek(fd, 0, SEEK_SET);
ssize_t d1 = read(fd1, str, 1024);
if (d1 < 0)
{
printf("读取失败\n");
}
printf("data = %s\n", str);
sleep(3);
}
}
return 0;
}
这里主要思路是创建两个文本分别一个读取一个写入 两个终端同时运行 达到信息交互的目的。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
//定义一个结构体
struct msg
{
char str[1024];
int type; //判断谁发送
};
int main(int argc, char const *argv[])
{
int fd = open("my.txt", O_RDWR);
struct msg *str = mmap(NULL, 1024, PROT_READ | PROT_WRITE, MAP_SHARED,
fd, 0);
pid_t pid = fork();
if (pid > 0)
{
//打印映射空间中类型为1的数据
while (1)
{
if (str->type == 1)//接收类型为1 的数据
{
printf("%s\n", str->str);
bzero(str, sizeof(struct msg));
}
}
}
if (pid == 0)
{
while (1)
{
str->type = 2;
scanf("%s", str->str);//放入类型为2的数据
}
}
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>
//定义一个
struct msg
{
char str[1024];
int type; //判断谁发送
};
int main(int argc, char const *argv[])
{
int fd = open("my.txt", O_RDWR);
struct msg *str = mmap(NULL, 1024, PROT_READ | PROT_WRITE, MAP_SHARED,
fd, 0);
pid_t pid = fork();
if (pid > 0)
{
//打印映射空间中类型为2的数据
while (1)
{
if (str->type == 2)
{
printf("%s\n", str->str);
bzero(str, sizeof(struct msg));
}
}
}
if (pid == 0)
{
while (1)
{
str->type = 1;
scanf("%s", str->str);//放入类型为1的数据
}
}
return 0;
}
运行效果:
这里主要思路是创建文本并映射到内存空间中,利用结构体一个标志位 一个读取1一个写入2 两个终端同时运行 达到信息交互的目的。