Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Napisz program, w którym dwa procesy będą zapisywały do jednego pliku, a trzy będą odczytywały. Zastosuj zajmowanie zalecane do synchronizacji pracu procesów.
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/file.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <wait.h>
- #include <string.h>
- #define PATHNAME "08_file"
- #define BUFFER_SIZE 128
- #define NUMBER_OF_WRITERS 2
- #define NUMBER_OF_READERS 3
- #define MSG_TO_SAVE "Wiadomosc nr "
- void error_exit(const char *message)
- {
- perror("message");
- exit(EXIT_SUCCESS);
- }
- void write_to_file(int fd, const char *msg)
- {
- if(flock(fd, LOCK_EX) == -1)
- error_exit("flock_ex");
- if(write(fd, msg, strlen(msg)) == -1)
- error_exit("write");
- printf("Zapisano do pliku!\n");
- if(flock(fd, LOCK_UN) == -1)
- error_exit("flock_un");
- }
- void read_from_file(int fd)
- {
- lseek(fd, 0, SEEK_SET);
- ssize_t status;
- char buffer[BUFFER_SIZE];
- if(flock(fd, LOCK_SH) == -1)
- error_exit("flock_sh");
- printf("Odczytano z pliku:\n");
- for(;;) {
- memset(buffer, '\0', BUFFER_SIZE);
- status = read(fd, buffer, BUFFER_SIZE-1);
- if(status == -1)
- error_exit("read");
- else if(status == 0)
- break;
- else
- printf("%s", buffer);
- }
- if(flock(fd, LOCK_UN) == -1)
- error_exit("flock_un");
- }
- int main(void)
- {
- pid_t pids;
- int fd;
- char write_buffer[strlen(MSG_TO_SAVE)+1];
- if((fd = open(PATHNAME, O_RDWR | O_CREAT | O_TRUNC, 0755)) == -1)
- error_exit("open");
- for(int i = 0; i < NUMBER_OF_WRITERS + NUMBER_OF_READERS; i++) {
- pids = fork();
- if(pids == -1)
- error_exit("fork");
- else if(pids == 0){
- printf("Proces nr: %d\n", i+1);
- if(i < NUMBER_OF_WRITERS) {
- sprintf(write_buffer, "%s%d\n", MSG_TO_SAVE, i);
- write_to_file(fd, write_buffer);
- }
- else {
- read_from_file(fd);
- }
- return EXIT_SUCCESS;
- }
- }
- for(int i = 0; i < NUMBER_OF_WRITERS + NUMBER_OF_READERS; i++)
- if(wait(NULL) == -1)
- error_exit("wait");
- return EXIT_SUCCESS;
- }
Add Comment
Please, Sign In to add comment