B进程的读代码:
#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 data_fd;
int res;
int open_mode = O_RDONLY;
char buffer[BUFFER_SIZE + 1];
int bytes_read = 0;
int bytes_write=0;
memset(buffer, '\0', sizeof(buffer));//申请内存空间
// 以只写方式建立保存数据的文件
data_fd = open("DataFormFIFO.txt", O_WRONLY | O_CREAT, 0644);
printf("Process B %d opening FIFO O_RDONLY\n", getpid());
pipe_fd = open(FIFO_NAME, open_mode);
printf("Process B %d result %d\n", getpid(), pipe_fd);
if (pipe_fd != -1) {
do {
res = read(pipe_fd, buffer, BUFFER_SIZE);
bytes_write = write(data_fd, buffer, res);
bytes_read += res;
} while (res > 0);
(void)close(pipe_fd);
(void)close(data_fd);
}
else {
exit(EXIT_FAILURE);
}
printf("Process B %d finished, %d bytes read\n", getpid(), bytes_read);
exit(EXIT_SUCCESS);
}
#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];
const char some_data[] = "张江伟020312297\n";
// 如果管道文件不存在,那么就创建管道
if (access(FIFO_NAME, F_OK) == -1) {
res = mkfifo(FIFO_NAME, 0777);//0777表示文件的权限,所有人都可以对其进行写执行操作。
//如果返回的是0,那么就创建成功,创建失败就是-1
if (res != 0) {
fprintf(stderr, "无法创建文件 %s\n", FIFO_NAME);//stdder是标准错误输出
exit(EXIT_FAILURE);
}
}
printf("Process A %d opening FIFO O_WRONLY\n", getpid()); // 如果文件打开了,那么我们就输出一下是那个进程打开的这个文件
pipe_fd = open(FIFO_NAME, open_mode);//这个第一个参数就是文件的完整路径,open_mode 就是的打开方式。O_WRONLY就是读写方式,调用失败返回是-1
printf("Process A %d result %d\n", getpid(), pipe_fd);
if (pipe_fd != -1) {//表示调用成功。返回的是文件的最小描述符
while(bytes_sent < TEN_MEG) {//表示现在的内容小于10MB缓冲区。
res = write(pipe_fd, some_data, strlen(some_data));//写入文件中
if (res == -1) {//如果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 A %d finished\n", getpid());
exit(EXIT_SUCCESS);
}