#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
// Define a buffer with size 64
char buffer[64];
// Define the path to the device
#define DEV_PATH "/dev/ko_dev"
// Main function
int main()
{
// Open the device with read and write permissions
int fd = open(DEV_PATH, O_RDWR);
// If the device fails to open, print an error message and return -1
if (fd < 0)
{
printf("open %s failed\n", DEV_PATH);
return -1;
}
// Get the process ID
pid_t pid = getpid();
// Infinite loop
while (1)
{
// Generate a random number between 5 and 12
int Num = rand() % 8 + 5;
// Fill the buffer with random characters
for (int i = 0; i < Num; i++)
buffer[i] = rand() % sizeof(char);
// Attempt to write to the device
ssize_t written = write(fd, buffer, Num);
// Check if the write was successful
if (written == -1)
{
perror("write failed");
break;
}
// Print the process ID, the number of characters requested to write, and the actual number of characters written
printf("Producer1 pid = %d requested to write %d characters, actually wrote %ld characters\n", pid, Num, written);
// If buffer is full, print a message every second
if (written == 0)
{
while (1)
{
printf("Buffer is full\n");
sleep(1);
}
}
// Sleep for 1 second
sleep(1);
}
// Close the device
close(fd);
// Return 0 to indicate successful execution
return 0;
}
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
// Define a buffer with size 64
char buffer[64];
// Define the path to the device
#define DEV_PATH "/dev/ko_dev"
// Main function
int main()
{
// Open the device with read and write permissions
int fd = open(DEV_PATH, O_RDWR);
// If the device fails to open, print an error message and return -1
if (fd < 0)
{
printf("open %s failed\n", DEV_PATH);
return -1;
}
// Get the process ID
pid_t pid = getpid();
// Infinite loop
while (1)
{
// Generate a random number between 5 and 12
int Num = rand() % 8 + 5;
// Attempt to read from the device
ssize_t read_bytes = read(fd, buffer, Num);
// Print the process ID, the number of characters requested to read, and the actual number of characters read
printf("Consumer1 pid = %d requested to read %d characters, actually read %ld characters\n", pid, Num, read_bytes);
// If no data was read, print a message every second
if (read_bytes == 0)
{
while (1)
{
printf("No data available to read\n");
sleep(1);
}
}
// Sleep for 1 second
sleep(1);
}
// Close the device
close(fd);
// Return 0 to indicate successful execution
return 0;
}