87 lines
2.4 KiB
C
87 lines
2.4 KiB
C
|
//
|
||
|
// Written for Computer Networks and Systems lab classes
|
||
|
// AUTHOR : Sergiusz Warga
|
||
|
|
||
|
#include <fcntl.h>
|
||
|
#include <math.h>
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <sys/mman.h>
|
||
|
#include <sys/types.h>
|
||
|
#include <unistd.h>
|
||
|
#include <time.h>
|
||
|
|
||
|
#include "CircBuffer.h"
|
||
|
|
||
|
#define PI 3.14
|
||
|
#define SIG_FREQ 100
|
||
|
#define SAM_FREQ 2000
|
||
|
|
||
|
double get_sample(int signal_frequeuncy, int sampling_frequency, int sample_no) {
|
||
|
// TODO: Just a sketch, gotta rewrite
|
||
|
double step = 2.*PI/200;
|
||
|
return sin(sample_no*step);
|
||
|
}
|
||
|
|
||
|
_Noreturn void producer(int fd) { // That's something new I've learned and I think that
|
||
|
// function specifiers are cute.
|
||
|
printf("The producer has been called\n");
|
||
|
|
||
|
struct CircBuffer *buffer;
|
||
|
buffer = mmap(NULL, sizeof(struct CircBuffer), PROT_WRITE, MAP_SHARED, fd, 0);
|
||
|
if (buffer == MAP_FAILED) {
|
||
|
fprintf(stderr, "mmap: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
|
||
|
}
|
||
|
|
||
|
int i = 0;
|
||
|
int free_idx = 0;
|
||
|
|
||
|
struct timespec delay;
|
||
|
delay.tv_sec = 0;
|
||
|
delay.tv_nsec = 500000ULL*1; // 0.5ms == 500 000ns -> 2kHz
|
||
|
|
||
|
while (1) {
|
||
|
free_idx = buffer->info.free_idx; // For more readable code
|
||
|
buffer->data[free_idx] = get_sample(SIG_FREQ, SAM_FREQ, i+1); // Put a sample into the buffer
|
||
|
buffer->info.free_idx = (free_idx + 1 ) % buffer->info.size; // Increase the free-cell index
|
||
|
printf("CircBuffer[%d] = \t %lf\n", free_idx, buffer->data[free_idx]);
|
||
|
i = ++i % 200;
|
||
|
nanosleep(&delay, NULL);
|
||
|
}
|
||
|
|
||
|
}
|
||
|
|
||
|
int main(int argc, char *argv[]) {
|
||
|
|
||
|
//----- Create a shared memory -----
|
||
|
const char *memory_name = "/dsp";
|
||
|
int fd = shm_open(memory_name, O_CREAT | O_RDWR, 0777);
|
||
|
if (fd < 0) {
|
||
|
fprintf(stderr, "shm_open: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
printf("Shared memory file descriptor: %d\n", fd);
|
||
|
|
||
|
//----- Truncate memory to the buffer's size
|
||
|
|
||
|
if (ftruncate(fd, sizeof(struct CircBuffer)) < 0) {
|
||
|
fprintf(stderr, "ftruncate: \n");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
|
||
|
//----- Initialize the buffer -----
|
||
|
struct CircBuffer *buffer;
|
||
|
buffer = (struct CircBuffer *)mmap(NULL, sizeof(struct CircBuffer), PROT_WRITE, MAP_SHARED, fd, 0);
|
||
|
if (buffer == MAP_FAILED) {
|
||
|
fprintf(stderr, "mmap: ");
|
||
|
exit(EXIT_FAILURE);
|
||
|
}
|
||
|
buffer->info.size = sizeof(buffer->data)/sizeof(double);
|
||
|
buffer->info.free_idx = 0;
|
||
|
|
||
|
producer(fd);
|
||
|
|
||
|
return 0;
|
||
|
}
|