进程间的通信----有名管道fifo

来源:互联网 发布:清朝灭亡 知乎 编辑:程序博客网 时间:2024/05/16 01:01

write端:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <string.h>

int main(int argc, const char *argv[])
{
if(access("./myfifo",F_OK) < 0)
{
if(mkfifo("./myfifo",0644) < 0)
{
perror("mkfifo fail\n");
return -1;
}
}

int fd;
char buff[128] = "\0";
fd = open("./myfifo",O_RDWR,0644);
while(1)
{
printf("请输入信息:\n");
scanf("%s",buff);
if(write(fd,buff,sizeof(buff)) < 0);
{
perror("write fail\n");
return -1;
}
if(strcmp(buff,"quit") == 0)
{
sleep(1);
printf("以结束写入信息!\n");
return 0;
}
memset(buff,0,sizeof(buff));
}


return 0;
}


read端:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <string.h>

int main(int argc, const char *argv[])
{
if(access("./myfifo",F_OK) < 0)
{
if(mkfifo("./myfifo",0644) < 0)
{
perror("mkfifo fail\n");
return -1;
}
}

int fd;
char buff[128] = "\0";
fd = open("./myfifo",O_RDWR,0644);
while(1)
{
printf("读到的信息:");
if(read(fd,buff,sizeof(buff)) < 0)
{
perror("read fail\n");
return -1;
}
printf("%s\n",buff);
if(strcmp(buff,"quit") == 0)
{
printf("准备退出!\n");
return 0;
}

}
return 0;
}