Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Napisz dwa programy: pierwszy będzie generował losowe liczby i zapisywał je porcjami do pliku, drugi działając współbieżnie z pierwszym będzie odczytywał je i szukał wartości maksymalnej. Do blokowania fragmentów pliku należy użyć funkcji fcntl().
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <wait.h>
- #include <time.h>
- #define PATHNAME "10_file"
- #define HOW_MANY 6
- #define HOW_MUCH 5
- #define DELAY 500000
- void write_function(int fd)
- {
- struct flock file_lock;
- int numbers[HOW_MUCH];
- for(int i = 0; i < HOW_MANY; i++) {
- file_lock.l_type = F_WRLCK;
- file_lock.l_whence = SEEK_CUR;
- file_lock.l_start = 0;
- file_lock.l_len = sizeof(int) * HOW_MUCH;
- for(int j = 0; j < HOW_MUCH; j++)
- numbers[j] = (rand() % 100) + 1;
- if(fcntl(fd, F_SETLKW, &file_lock) == -1) {
- perror("fcntl");
- exit(EXIT_FAILURE);
- }
- if(write(fd, numbers, sizeof(int)*HOW_MUCH) == -1) {
- perror("write");
- exit(EXIT_FAILURE);
- }
- file_lock.l_type = F_UNLCK;
- if(fcntl(fd, F_SETLK, &file_lock) == -1) {
- perror("fcntl");
- exit(EXIT_FAILURE);
- }
- lseek(fd, 0, SEEK_SET);
- printf("Proces 1: Zapisano %d liczb\n", HOW_MUCH);
- usleep(DELAY);
- }
- }
- void read_function(int fd)
- {
- int numbers[HOW_MUCH];
- lseek(fd, 0, SEEK_SET);
- for(int i = 0; i < HOW_MANY; i++) {
- if(read(fd, numbers, sizeof(int)*HOW_MUCH) == -1) {
- perror("read");
- exit(EXIT_FAILURE);
- }
- printf("Proces 2: Odczytano liczby: ");
- for(int j = 0; j < HOW_MUCH; j++)
- printf("%d ", numbers[j]);
- printf("\n");
- lseek(fd, 0, SEEK_SET);
- usleep(DELAY);
- }
- }
- int main(void)
- {
- pid_t pid;
- int fd;
- srand(time(NULL));
- if((fd = open(PATHNAME, O_RDWR | O_CREAT | O_TRUNC, 0700)) == -1) {
- perror("open");
- return EXIT_FAILURE;
- }
- pid = fork();
- if(pid == -1) {
- perror("fork");
- return EXIT_FAILURE;
- }
- else if(pid == 0) {
- read_function(fd);
- }
- else {
- write_function(fd);
- }
- if(close(fd) == -1) {
- perror("close");
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
Add Comment
Please, Sign In to add comment