上机实验研究命名管道问题

来源:互联网 发布:淘宝返还的钱在哪里 编辑:程序博客网 时间:2024/04/29 05:15
Linux实验四
本次上机实验研究命名管道问题。
1.研究mkfifo命令,在工作目录建立一个命名管道文件myfifo,注意其属性。
所需的头文件:
#include<sys/types.h>
#include<sys/state.h>
函数原型:
int mkfifo(const char *filename,mode_t mode)
函数传入值:
filemame 要创建的管道
函数传入值:
mode O_RDONLY,O_WRONLY,O_RDWR,O_NONBLOCK,O_CREAT,O_EXCL
函数返回值:
成功:0,出错:-1;
2.编写一个c程序,其功能为打开建立的命名管道文件,并从中不断读取字符串,显示到屏幕上。这个程序可以认为是一个服务器程序,请在窗口中运行它
这里主要的问题是,我建立的myfifo权限不够,需要用shell中的chmod 666 myfifo去更改权限
程序代码:
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define FIFO "./myfifo"

int main()
{
int fd;
int flag;
char buf_read[100];
memset(buf_read,0,sizeof(buf_read));   /*clear the array by 0*/
/*make fifo*/
if((mkfifo(FIFO,O_CREAT|O_EXCL|O_RDWR|O_NONBLOCK)<0)&&(errno!=EEXIST))
        printf("Cannot creat fifo_server!/n");

fd=open(FIFO,O_RDONLY);/*open FIFO*/
if(fd==-1)
{
        printf("Cannot open FIFO!/n");
        perror("Open FIFO");
        exit(-1);
}

printf("Reading FIFO .......");
while(1)
{
memset(buf_read,0,sizeof(buf_read)); /*clear again with 0*/
if((flag=read(fd,buf_read,sizeof(buf_read)))==-1)
{
        printf("Read FIFO error!/n");
        break;
}
if(flag==0)
{
        printf("No data to read,it's the end of FIFO");
        break;
}
printf("%s",buf_read);
sleep(1);       /*read the data per second*/
}
unlink(FIFO);/*delete FIFO,when exit*/
return 0;
}
3.当上面的服务器程序运行的时候,可以从另外一个窗口运行cp命令,如cp a.c myfifo,则a.c的内容应该显示在另外运行服务器程序的命令窗口中。为什么?
因为a.c复制到myfifo中了,我们在第一步建立的是从myfifo读取数据的相当于服务器端,只是会从中读取数据。直到没有数据了停止。
4.设计一个c程序,读取任意一个文本文件,把内容写入命名管道myfifo中,以实现从服务器程序中显示。
思路:
通过带参数的main,比如./write_fifo  server.c这个格式,让server.c的内容写入到myfifo中,并且在运行着的服务器端显示出来。
本程序主要实现的是复制的功能,也就是把目标文件读到myfifo中
程序代码:
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define FIFO "./myfifo"

int main(int argc,char **argv)
{
int fd1,fd2,flag;
char buf_write[100];

if(argc!=2)
        perror("argument error/n");

fd1=open(argv[1],O_RDONLY);     /*Open the target*/
if(fd1==-1)
{
         printf("file %s can not opened/n",argv[1]);
         exit(-1);
}
fd2=open(FIFO,O_WRONLY);        /*Open FIFO*/
if(fd2==-1)
{
        printf("Cannot open FIFO!/n");
        perror("Open FIFO");
        exit(-1);
}
while(1)                        /*Write the target file to the FIFO*/
{
         flag=read(fd1,buf_write,sizeof(buf_write));
         write(fd2,buf_write,flag);
         if(flag!=sizeof(buf_write))
                break;
}
    close(fd1);
    close(fd2);

return 0;
}



原创粉丝点击