国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 服務(wù)器 > Linux服務(wù)器 > 正文

武林網(wǎng)淺析Linux命名管道的使用

2024-09-05 23:01:27
字體:
供稿:網(wǎng)友
Linux命名管道非常適合同一機(jī)器上兩個進(jìn)程之間傳遞數(shù)據(jù),其形式也是一個文件,但是讀取與寫入時遵循FIFO的原則。在使用命名管道時有兩種方式進(jìn)行讀/寫:阻塞與非阻塞。

使用命名管道很容易寫出生產(chǎn)者與消費(fèi)者的程序。下面這個程序摘自《Linux程序設(shè)計(jì)(第3版)》

producer.c

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

#define FIFO_NAME "/tmp/my_fifo"
#define BUFFER_SIZE PIPE_BUF
#define TEN_MEG (1024 * 1024 * 10)

int main()
{
int pipe_fd;
int res;
int open_mode = O_WRONLY;
int bytes_sent = 0;
char buffer[BUFFER_SIZE + 1];

if(access(FIFO_NAME,F_OK) == -1){
res = mkfifo(FIFO_NAME,0777);
if(res != 0){
fprintf(stderr,"Could not create fifo %s/n",FIFO_NAME);
exit(EXIT_FAILURE);
}
}

printf("Process %d opening FIFO O_WRONLY/n",getpid());
pipe_fd = open(FIFO_NAME,open_mode);
printf("Process %d result %d/n",getpid(),pipe_fd);

if(pipe_fd != -1){
while(bytes_sent < TEN_MEG){
res = write(pipe_fd,buffer,BUFFER_SIZE);
if(res == -1){
fprintf(stderr,"Write error on pipe/n");
exit(EXIT_FAILURE);
}
bytes_sent += res;
}
(void)close(pipe_fd);
}
else{
exit(EXIT_FAILURE);
}

printf("Process %d finished/n",getpid());
exit(EXIT_SUCCESS);
}


customer.c

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

#define FIFO_NAME "/tmp/my_fifo"
#define BUFFER_SIZE PIPE_BUF

int main()
{
int pipe_fd;
int res;

int open_mode = O_RDONLY;
char buffer[BUFFER_SIZE + 1];
int bytes_read = 0;

memset(buffer,'/0',sizeof(buffer));

printf("Process %d opening FIFO O_RDONLY/n",getpid());
pipe_fd = open(FIFO_NAME,open_mode);
printf("Process %d result %d/n",getpid(),pipe_fd);

if(pipe_fd != -1){
do{
res = read(pipe_fd,buffer,BUFFER_SIZE);
bytes_read += res;
}while(res > 0);
(void)close(pipe_fd);
}
else{
exit(EXIT_FAILURE);
}

printf("Process %d finished, %d bytes read/n",getpid(),bytes_read);
exit(EXIT_SUCCESS);
}

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 龙南县| 从化市| 社旗县| 恩平市| 页游| 娱乐| 隆子县| 元朗区| 宜良县| 连云港市| 新河县| 萍乡市| 石城县| 苍溪县| 礼泉县| 元谋县| 开封县| 壶关县| 酉阳| 石首市| 甘德县| 临邑县| 客服| 保德县| 蕉岭县| 固始县| 东源县| 县级市| 驻马店市| 中方县| 海南省| 海兴县| 元江| 马龙县| 岳阳市| 尚志市| 清远市| 新河县| 哈尔滨市| 南岸区| 天门市|