Skip to content

Instantly share code, notes, and snippets.

@yanisurbis
Last active November 6, 2022 14:45
Show Gist options
  • Save yanisurbis/ed3059ff9c20a4aa31258034c2ed78a8 to your computer and use it in GitHub Desktop.
Save yanisurbis/ed3059ff9c20a4aa31258034c2ed78a8 to your computer and use it in GitHub Desktop.
// cache
// use segment address to send file, make segment available for other threads right after exit
// the error is in this function
int send_file_through_shm(cache_thread_ctx *ctx) {
long maxBytesToRead = ctx->seg_size - 1;
long n_loops = ctx->file_size / maxBytesToRead;
n_loops += (ctx->file_size % maxBytesToRead) == 0 ? 0 : 1;
long res = 0;
for (long i = 0, offset = 0; i < n_loops; i++) {
sem_wait(ctx->sem_write);
if ((res = pread(ctx->fd, ctx->seg_addr, maxBytesToRead, offset)) < 0) {
perror("pread:");
return -1;
}
ctx->seg_addr[res] = '\0';
offset += res;
sem_post(ctx->sem_read);
}
return 0;
}
// proxy
// receiving function, just for the context
ssize_t recv_file(gfcontext_t *ctx, thread_ctx *thr_ctx, mq_resp_msg *response) {
long segsize = thr_ctx->system_resources->segsize;
long file_size = response->file_size;
char *addr = thr_ctx->system_resources->segments_pool[response->segment_id].seg_addr;
sem_t *sem_read = thr_ctx->system_resources->segments_pool[response->segment_id].sem_read;
sem_t *sem_write = thr_ctx->system_resources->segments_pool[response->segment_id].sem_write;
long bytes_transferred = 0;
long bytes_sent = 0;
while(bytes_transferred < file_size){
sem_wait(sem_read);
long left_to_transfer = file_size - bytes_transferred;
long bytes_to_send = left_to_transfer >= segsize ? segsize - 1 : left_to_transfer;
bytes_sent = gfs_send(ctx, addr,bytes_to_send);
if (bytes_sent != bytes_to_send){
sem_post(sem_write);
fprintf(stderr, "handle_with_file write error");
return SERVER_FAILURE;
}
bytes_transferred += bytes_sent;
sem_post(sem_write);
}
return bytes_transferred;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment