0
我目前正試圖實現一個併發服務器(即通過派生新子進程來處理多個進程)。使用fnctl()鎖定和解鎖文件進行讀寫(多個進程)
每個客戶端執行讀取/寫入請求以從位於服務器中的file.txt讀取。我目前使用fnctl()
來處理同步,即。我可以有多個讀取,但只有一個寫入。
這是我做了什麼至今的樣本代碼:
{
FILE *file = fopen("file.txt", "w+");
fd = fileno(file);
printf("\nThis is the file descriptor : %d\n", fd);
if(file == NULL)
printf("File cannot be opened");
printf("\nLocking!!!!");
//initliazing the flock structure
memset(&lock, 0, sizeof(lock)); //setting 0 as a value
lock.l_type = F_WRLCK; //F_RDLCK, F_WRLCK, F_UNLCK
lock.l_whence = SEEK_SET; //SEEK_SET, SEEK_CUR, SEEK_END
lock.l_start = 0; //offset from l_whence
lock.l_len = 0; //length, 0 = to EOF
lock.l_pid = getpid(); //the processes's PID
//placing a write lock on the file
fcntl(fd, F_SETLKW, &lock);
printf("\nLocked-------");
fwrite(buff + 1, 1, strlen(buff) - 1, file);
//lock_realease(&l);
printf("\nHit enter to unlock the file !");
getchar();
printf("\nFinished writing so we can unlock file !");
//Releasing lock
lock.l_type = F_UNLCK; //unlocks the region of the file
fcntl(fd, F_SETLKW,&lock);
printf("\nFile unlocked!");
}
有人能指導我,如果我在正確的方向嗎?
你能給我一些關於如何執行這樣的錯誤處理和請等待的指導嗎? – user3770009
對於錯誤處理,您需要檢查您所調用功能的手冊。通常,你必須檢查你調用的所有函數的返回值。對於等待而言,這更復雜。你需要找到一個功能,讓你的孩子睡覺和一個循環,並以某種方式來注意當你等待了太久。 –
謝謝我會嘗試 – user3770009