c - Writing logs to a file in multithreaded application -
i've written server-client application. now, have write happens on server log file. server written in c. can write happens screen using printf.
so i'll have use fprintf instead of printf. question how should handle file?
i have server.c
source file there main function
here basic structure of server application:
server.c
//.. code int main(...) { //some code //initialize variables //bind server //listen server on port while(1) { //accept client int check = pthread_create(&thread, null, handle_client,&ctx);//create new thread //.. }//end while return exit_success; }//end main
handle_client
function handles clients in new thread.
how should make server log? have 1 text file example serverlog.log
, there many clients on server. how should handle multiple access file?
one way create file when start server, open it, write in it, close it. if client wants write in file, should open file write in , close it.
but there still problem when more clients want write in file....
a common solution have printf
-like function, writes output first buffer, locks semaphore, actual writing file, , unlocks semaphore. if worried actual writing being slow, can instead have queue log messages gets inserted, , let thread take items queue , write them file, still have protect queue e.g. semaphore, should quicker doing i/o.
as actual file, either open in main thread , leave open. or if have special logging thread queue let thread opening. anyway, don't need keep opening/closing every time want write it, important part protect being written multiple threads simultaneous.
Comments
Post a Comment