效果
功能:user1和user2互发消息。
运用的知识
- 创建进程
- 文件打开和读取
- linux管道文件
具体实现代码
1.首先在同一个文件夹下创建两个管道文件
mkfifo f1
mkfifo f2
2.写上代码
user1.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//文件处理相关库
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t pid = fork();
if(pid < 0){
perror("fork");
return -1;
}
else if(pid == 0){
//发消息给user2
int fd = open("./f2",O_WRONLY);
char buf[20]={0};
while(1){
gets(buf);
if(strcmp(buf,"!q")==0){
exit(0);
}
write(fd, buf, strlen(buf));
}
}
else{
printf("user1---------------------\n");
//接受user2发过来的消息
int fd = open("./f1",O_RDONLY);
char buf[100] = {0};
int n;
while(1){
n = read(fd, buf, sizeof(buf));
if(n==0) break;
printf("user2: %s\n", buf);
memset(buf, 0, sizeof(buf));
}
}
return 0;
}
user2的代码和user1的差不多,就是提示文本不同而已
user2.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t pid = fork();
if(pid < 0){
perror("fork");
return -1;
}
else if(pid == 0){
//发消息给user1
int fd = open("./f1",O_WRONLY);
char buf[20]={0};
while(1){
gets(buf);
if(strcmp(buf,"!q")==0){
exit(0);
}
write(fd, buf, strlen(buf));
}
}
else{
//接受user1发过来的消息
printf("user2-------------\n");
int fd = open("./f2",O_RDONLY);
char buf[100] = {0};
int m;
while(1){
m = read(fd, buf, sizeof(buf));
if(m==0) break;
printf("user1:%s\n", buf);
memset(buf, 0, sizeof(buf));
}
}
return 0;
}
3.编译运行
gcc user1.c -o user1
gcc user2.c -o user2
打开两个终端,第一个终端输入 ./user1 第二个输入 ./user2
完成。
ctrl+c 停止聊天