Я пытаюсь читать и писать из общего файла между процессами. Файл содержит 6 строк, которые должны быть прочитаны, а затем одна строка должна вставить новую строку. Чтобы быть более точным, я хочу, чтобы мой процесс чтения выполнялся одновременно, но процесс записи должен выполняться один за другим. По этой причине я использую один семафор для синхронизации своих процессов. Во-первых, я создаю 7 детей. Затем, используя для l oop, я вызываю функцию, которая читает строку из файла и затем печатает ее. Если последний процесс чтения завершен, он выполняет операцию UP, которая перехватывается последним дочерним элементом, который записывает последнюю строку в файле.
Это мой файл:
Hello ! Это общий файл для процессов!
Здравствуйте! Это общий файл для процессов!
Здравствуйте! Это общий файл для процессов!
Здравствуйте! Это общий файл для процессов!
Здравствуйте! Это общий файл для процессов!
Здравствуйте! Это общий файл между процессами!
и это мой код:
#include <stdio.h> /* printf() */
#include <stdlib.h> /* exit(), malloc(), free() */
#include <sys/types.h> /* key_t, sem_t, pid_t */
#include <sys/shm.h> /* shmat(), IPC_RMID */
#include <errno.h> /* errno, ECHILD */
#include <semaphore.h> /* sem_open(), sem_destroy(), sem_wait().. */
#include <fcntl.h> /* O_CREAT, O_EXEC */
#include <sys/mman.h>
#include <unistd.h>
#include <sys/wait.h>
sem_t wrt;
void read_print(FILE *file)
{
char c[1000];
fscanf(file, "%[^\n]", c); //reading a single line from the file
printf("%s\n", c); //and printing it.
}
int main()
{
FILE *fp;
int i, counter = 0;
pid_t pid[7];
fp = fopen("shared_file.txt", "r+");
sem_init(&wrt, 1, 1); //initialiing the semaphore to be shared between$
if(fp == NULL)
{
printf("Error opening file!");
exit(1);
}
/* creating the child processes */
for(i = 0; i <7; i++)
{
pid[i] = fork();
if(pid[i] == 0)
break;
}
for(i = 0; i<6; i++)
if(pid[i] == 0) //if the processes is a child process
{
read_print(fp); //call the function
counter++; //increment the process counter by 1
if(counter == 6) //if we are at the final process
sem_post(&wrt); //UP operation
exit(0); //and then exits
}
if(pid[6] == 0) //if the final process is a child
{
sem_wait(&wrt); //DOWN operation
fprintf(fp, "...and this is the final line."); //writes a new $
exit(0);
}
fclose(fp); //closes the file.
return 0;
}