2、 有名管道
有名管道可用于兩個無關(guān)的進(jìn)程之間的通信。它的實(shí)現(xiàn)函數(shù)是:
int mkfifo(const char *filename, mode_t mode)
//創(chuàng)建一個名為filename的管道,模式可選為讀或?qū)懛绞?,阻塞或非阻塞方式等?br>下面一個實(shí)例演示了mkfifo的使用。Fifo_read.c不斷從管道文件里讀數(shù)據(jù),fifo_write.c往管道文件里寫數(shù)據(jù)。改變sleep的值也會產(chǎn)生類似上面進(jìn)程同步的問題,而會發(fā)現(xiàn)一些緩沖區(qū)的特性。
兩個程序用gcc編譯后在兩個終端里運(yùn)行。
//---------------------------------------------------------------------------------------------------
//fifo_read.c
//創(chuàng)建有名管道,演示兩個不相關(guān)的進(jìn)程之間的通信
//int mkfifo(const char *filename, mode_t mode)
#include
#include
#include
#include
#include
#include
#include
#include
#define FIFO "/home/huang/myfifo"
int main(int argc,char **argv)
{
int fd;
int nread;
char buf_r[100];
if(mkfifo("/home/huang/myfifo",O_CREAT|O_EXCL)
{
perror("mkfifo:");
printf("cann't create fifoserver\n");
return -1;
}
printf("Preparing for reading bytes...\n");
fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);
if(fd==-1)
{
perror("open!\n");
exit(1);
}
while(1)
{
memset(buf_r,0,sizeof(buf_r));
if((nread=read(fd,buf_r,sizeof(buf_r)))==-1)
{
if(errno==EAGAIN)
printf("no data yet\n");
}
printf("read %s from FIFO\n",buf_r);
sleep(1);
}
pause();
unlink(FIFO);
}
//------------------------------------------------------------------------------------------------------------------
//fifo_write.c
//創(chuàng)建有名管道,演示兩個不相關(guān)的進(jìn)程之間的通信
//int mkfifo(const char *filename, mode_t mode)
#include
#include
#include
#include
#include
#include
#include
#include
#define FIFO "/home/huang/myfifo"
int main(int argc, char **argv)
{
int fd;
char w_buf[100];
int nwrite;
if(argc==1)
{
printf("please send some message\n");
exit(1);
}
fd=open(FIFO,O_WRONLY|O_NONBLOCK,0);
if(fd==-1)
{
if(errno==ENXIO)
printf("open error;no reading process\n");
perror("open:");
return -1;
}
memset(w_buf,'a',sizeof(w_buf));
printf("sizeof(w_buf)=%d\n",sizeof(w_buf));
while(1)
{
if((nwrite=write(fd,w_buf,strlen(w_buf)))==-1)
{
if(errno==EAGAIN)
printf("The FIFO has not been write yet.\n");
perror("write");
// else
// printf("error in writting!\n");
}
else
printf("write %s to the FIFO\n",w_buf);
sleep(2);
}
close(fd);
}
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點(diǎn)擊舉報。