本程序是一个使用FIFO进行进程间通信的典型程序lucy.c创建了FIFO write──fifo用于向程序peter.c发送信息:程序创建了FIFO read-fifo,用于向lucy.c发送消息。编译本程序,先运行peter.c再运行lucy.c就可以了。
源程序如下:
//filename:lucy.c
#include
#include
#include
#include
#include
#include
#include
#include
int main(viod)
{
char write_fifo_name[]="write-fifo";
char read_fifo_name[]="read-fifo";
int write_fd,read_fd;
char buf[256];
int len;
struct stat_buf;
int ret=mkfifo(write_fifo_name,S_IRUSR | S_IWUSR);
if(ret==-1)
{printf("failed to create FIFO %s:%s\n",write_fifo_name,strerror(errno));
exit(-1);
}
write_fd=open(write_fifo_name,O_WRONLY);
if(write_fd==-1)
{printf("failed to open FIFO %s:%s\n",write_fifo_name,strerror(errno));
exit(-1);}
while((read_fd=open(read_fifo_name,O_RDONLY))==-1)
{sleep(1);}
while(1){printf("lucy:");
fgets(buf,256,stdin);
buf[strlen(buf)-1]='\0';
if(strncmp(buf,"quit",4)==0)
{close(write_fd);
unlink(write_fifo_name);
close(read_fd);
exit(0);
}
write(write_fd,buf,strlen(buf));
len=read(read_fd,buf,256);
if(len>0)
{
buf[len]='\0';
printf("perter:%s\n",buf);
}
}
}
//filename:peter.c
#include
#include
#include
#include
#include
#include
#include
#include
int main(viod)
{
char write_fifo_name[]="read-fifo";
char read_fifo_name[]="write-fifo";
int write_fd,read_fd;
char buf[256];
int len;
//struct stat_buf;
int ret=mkfifo(write_fifo_name,S_IRUSR | S_IWUSR);
if(ret==-1)
{
printf("failed to create FIFO %s:%s\n",write_fifo_name,strerror(errno));
exit(-1);
}
while((read_fd=open(read_fifo_name,O_RDONLY))==-1)
{
sleep(1);
}
write_fd=open(write_fifo_name,O_WRONLY);
if(write_fd==-1)
{
printf("failed to open FIFO %s:%s\n",write_fifo_name,strerror(errno));
exit(-1);
}
while(1)
{
len=read(read_fd,buf,256);
if(len>0)
{
buf[len]='\0';
printf("lucy:%s\n",buf);
}
printf("peter:");
fgets(buf,256,stdin);
buf[strlen(buf)-1]='\0';
if(strncmp(buf,"quit",4)==0)
{
close(write_fd);
unlink(write_fifo_name);
close(read_fd);
exit(0);
}
write(write_fd,buf,strlen(buf));
}
}
阅读(3094) | 评论(0) | 转发(0) |