Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Zademonstruj działanie funkcji flock() na przykładzie, w którym kilka procesów współbieżnych będzie się ubiegało o możliwość zapisu lub odczytu z pliku.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/file.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <wait.h>
- #include <time.h>
- #include <stdbool.h>
- #include <string.h>
- #define FILENAME "04_file"
- #define NUMBER_OF_PROCESSES 5
- const char *write_text = "Wiadomosc do zapisania\n";
- void writer_function(int fd)
- {
- if(flock(fd, LOCK_EX) == -1) {
- perror("flock_ex");
- exit(EXIT_FAILURE);
- }
- if(write(fd, write_text, strlen(write_text)) == -1) {
- perror("write");
- exit(EXIT_FAILURE);
- }
- printf(" Zapisano do pliku!\n");
- if(flock(fd, LOCK_UN) == -1) {
- perror("flock_un");
- exit(EXIT_FAILURE);
- }
- }
- void reader_function(int fd)
- {
- char read_buffer[16];
- ssize_t read_status;
- if(flock(fd, LOCK_SH) == -1) {
- perror("flock_sh");
- exit(EXIT_FAILURE);
- }
- printf(" Odczytano z pliku!\n");
- for(;;) {
- read_status = read(fd, read_buffer, 16);
- if(read_status == -1) {
- perror("read");
- exit(EXIT_FAILURE);
- }
- else if(read_status == 0){
- break;
- }
- else
- printf(" %s", read_buffer);
- }
- if(flock(fd, LOCK_UN) == -1) {
- perror("flock_un");
- exit(EXIT_FAILURE);
- }
- }
- int main(void)
- {
- int fd;
- pid_t pid;
- bool reader_writer;
- srand(time(NULL));
- if((fd = open(FILENAME, O_RDWR | O_TRUNC, 0600)) == -1) {
- perror("open");
- return EXIT_FAILURE;
- }
- for(int i = 0; i < NUMBER_OF_PROCESSES; i++) {
- reader_writer = rand() % 2;
- pid = fork();
- if(pid == -1) {
- perror("fork");
- return EXIT_FAILURE;
- }
- else if(pid == 0) {
- if(reader_writer){
- printf("Proces nr %d:\n", i);
- writer_function(fd);
- }
- else{
- printf("Proces nr %d:\n", i);
- reader_function(fd);
- }
- return EXIT_SUCCESS;
- }
- }
- for(int i = 0; i < NUMBER_OF_PROCESSES; i++) {
- if(wait(NULL) == -1) {
- perror("wait");
- return EXIT_FAILURE;
- }
- }
- if(close(fd) == -1) {
- perror("close");
- return EXIT_FAILURE;
- }
- return EXIT_SUCCESS;
- }
Add Comment
Please, Sign In to add comment