I got a server that is always running, it creates a log file that receives via named pipe one argument and stores it on the log.txt file.
Clients sent a message via argument to the named pipe.
cliente side i guess its ok, if i cat /tmp/talk its there the full message, but on the server its only storing the first char. why is that?
And a simplier question, is there a better way to implement the server cycle to check the pipe?
client
int main(int argc, char const *argv[]){
char *myfifo = "/tmp/talk"; int fd,n;
fd = open(myfifo,O_WRONLY);
write(fd,argv[1],strlen(argv[1])+1); printf("Sent to server: %s \n",argv[1]);
close(fd);
}
server
int main(int argc, char const *argv[]){
char *myfifo = "/tmp/talk";
char buffer[2024];
//char *log = "log.txt";
int fd,n;
mkfifo(myfifo, 0666);
int log = open("log.txt",O_CREAT|O_APPEND|O_WRONLY, 0666);
fd = open(myfifo,O_RDONLY);
while(1) {
if(n = read(fd,buffer,1024)>0) {
write(log,buffer,n);
write(1,buffer,n);
//printf("Client connected sent: %s",buffer);
}
}
}
n = read(fd,buffer,1024)>0
evaluates like
n = (read(fd,buffer,1024)>0)
so 1
is stored in n
(instead of the number of bytes read) if read returns a positive value. Use instead:
(n = read(fd,buffer,1024))>0
as conditional, then it should work as expected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.