feat[OS/lab5]: completed part B
This commit is contained in:
66
OSs/lab5/part-B/server.c
Normal file
66
OSs/lab5/part-B/server.c
Normal file
@ -0,0 +1,66 @@
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
|
||||
#include "common.h"
|
||||
|
||||
int server(int fd_read, int fd_write);
|
||||
|
||||
int main()
|
||||
{
|
||||
FAIL_ON(mknod(FIFO_SERVER_PATH, S_IFIFO | 0666, 0) < 0);
|
||||
printf("created %s\n", FIFO_SERVER_PATH);
|
||||
FAIL_ON(mknod(FIFO_CLIENT_PATH, S_IFIFO | 0666, 0) < 0);
|
||||
printf("created %s\n", FIFO_CLIENT_PATH);
|
||||
|
||||
int read_fd, write_fd;
|
||||
FAIL_ON((read_fd=open(FIFO_SERVER_PATH, O_RDONLY)) < 0);
|
||||
FAIL_ON((write_fd=open(FIFO_CLIENT_PATH, O_WRONLY)) < 0);
|
||||
|
||||
return server(read_fd, write_fd);
|
||||
}
|
||||
|
||||
#define BUF_SIZE 256
|
||||
|
||||
/**
|
||||
* Performs server actions
|
||||
*
|
||||
* @fd_read - pipe to read from
|
||||
* @fd_write - pipe to write to
|
||||
*
|
||||
* returns 0 on success or -errno on fail
|
||||
*/
|
||||
int server(int fd_read, int fd_write)
|
||||
{
|
||||
char buf[BUF_SIZE] = {0};
|
||||
size_t n = read(fd_read, buf, BUF_SIZE);
|
||||
if (n == 0) return -EFAULT;
|
||||
FILE *f = fopen(buf, "r");
|
||||
// не 100% правильно, но наиболее вероятно
|
||||
if (f == NULL) {
|
||||
const char error_msg[] = "Can't open requested file\n";
|
||||
struct custom_ds payload = {
|
||||
.hdr.len = sizeof(error_msg),
|
||||
.hdr.type = DS_FAIL,
|
||||
};
|
||||
strncpy(payload.msg, error_msg, sizeof(error_msg));
|
||||
send_msg(fd_write, &payload);
|
||||
goto epilog;
|
||||
}
|
||||
|
||||
while ((n = fread(buf, sizeof(buf[0]), BUF_SIZE, f)) > 0) {
|
||||
struct custom_ds payload = {
|
||||
.hdr.len = n,
|
||||
.hdr.type = DS_MESSAGE,
|
||||
};
|
||||
strncpy(payload.msg, buf, n);
|
||||
send_msg(fd_write, &payload);
|
||||
memset(buf, 0, sizeof(buf));
|
||||
}
|
||||
|
||||
epilog:
|
||||
fclose(f);
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user