c - Reading from FIFO(named pipe) in While loop without body -
im trying make tic tac toe game server-client in c. on server side have read fifo(named pipe) 2 pids. made loop run until read (from fifo) return value different zero(mean client wrote pid fifo).
i have reason, on laptop it's not working , on buddy laptop it's working. same code!! have no clue why happening.
and when add body first while loop , put printf("1"); in it. it's work , pid1 reads pid fifo.
the code of server:
#include <stdio.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> void main() { int fd,shmid; key_t shmkey; void *shm_add; pid_t pid,pid1=0,pid2=0; mkfifo("fifo_clienttoserver",400); fd=open("fifo_clienttoserver",o_nonblock | o_rdonly); pid=fork(); if(pid==0) { while(read(fd,&pid1,sizeof(pid_t))==0); //(1) } else { wait(); while(read(fd,&pid2,sizeof(pid_t))==0) { if(pid2!=pid1) break; } remove("fifo_clienttoserver"); } printf("\nfirst pid= %d\nsecond pid= %d\n",pid1,pid2); }
the code of client:
#include <stdio.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <signal.h> #include <stdbool.h> void my_handler(int signum); bool over=false; int board[3][3]={{0,0,0},{0,0,0},{0,0,0}}; char tav; static bool first=false; void main() { int fd; pid_t pid1=getpid(); signal(sigusr2, my_handler); fd=open("fifo_clienttoserver",o_wronly); write(fd,&pid1,sizeof(pid_t)); printf("%d\n",pid1); while(!over); } void my_handler(int signum) { char geth; printf("1"); //check if signal sigusr2. if (signum == sigusr2) { if(!first) { tav='x'; printf("x"); first=true; } else { tav='c'; printf("c"); } } }
it's weird , dont know how deal it! when change line (1) while(read(fd,&pid1,sizeof(pid_t))==0){printf("1");}
it's working , pid1
value.
please me.
man read
:
if process has pipe open writing , o_nonblock set, read() shall return -1 , set errno [eagain].
so, while
loop breaks without read.
in event, busy waiting bad. drop o_nonblock or use
fd_set readfds; fd_zero(&readfds); fd_set(fd, &readfds); select(fd+1, &readfds, null, null, null);
before read()
.
Comments
Post a Comment