1.主要实现
lucy进程和pete进程间的通信交流。
代码就在这里,我自己在测试时遇到过bug,大家一块交流改进。
pete部分:
//pete
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
int fd;
char buf[40];
pid_t pid=fork();
if(pid>0)
{
while(1)
{
mkfifo("fifo1",0777);
fd=open("./fifo1",O_WRONLY,0666);
if(fd<0)
{
perror("open error");
exit(0);
}
//pete发送消息给lucy
printf("pete:");
//fflush(stdout);
scanf("%s",&buf);
write(fd,buf,sizeof(buf));
}
}
if(pid==0)
{ while(1)
{
mkfifo("fifo",0777);
fd=open("./fifo",O_RDONLY,0666);
if(fd<0)
{
perror("open error");
exit(0);
}
//pete接收lucy的消息
memset(buf,0,sizeof(buf));
read(fd,buf,sizeof(buf));
printf("\r lucy :%s\n",buf);
}
_exit(0);
}
close(fd);
return 0;
}
lucy部分:
//lucy
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
int fd;
char buf[40];
pid_t pid=fork();
if(pid>0)
{
while(1)
{
mkfifo("fifo",0777);
fd=open("./fifo",O_WRONLY,0666);
if(fd<0)
{
perror(“open error”);
exit(0);
}
//lucy发送消息给pete
printf("lucy:");
fflush(stdout);
scanf("%s",&buf);
write(fd,buf,sizeof(buf));
}
}
if(pid==0)
{ while(1)
{
mkfifo("fifo1",0777);
fd=open("./fifo1",O_RDONLY,0666);
if(fd<0)
{
perror("open error");
exit(0);
}
//接收pete的消息
memset(buf,0,sizeof(buf));
read(fd,buf,sizeof(buf));
printf("\r pete :%s\n",buf);
}
_exit(0);
}
close(fd);
return 0;
}