命名管道函数FIFO编写错误
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#define FIFO_PATH "/opt/fifo_test"
void pid_printf(char *format,...)
{
va_list ap;
va_start(ap,format);
printf("[%d]:",getpid());
vprintf(format,ap);
}
void server()
{
char buf[256]={0};
int fd;
int count,status;
if(mkfifo(FIFO_PATH,0600))
{
perror("mkfifo");
}
pid_printf("The server is listening on /opt/fifo_test.\n");
fd = open(FIFO_PATH,O_RDONLY);
pid_printf("client has connected.\n");
while(1)
{
count = 0;
while(count<(sizeof(buf)-1))
{
status = read(fd,buf+count,1);
if(status<1)
{
pid_printf("read EOF,parent excting \n");
goto parent_exit;
}
if(buf[count]=='\n')
{
break;
}
count++;
}
pid_printf("Receive message:%s",buf);
}
parent_exit:
close(fd);
unlink(FIFO_PATH);
}
void client(char **argv)
{
int fd;
char buf[256];
fd = open(argv[1],O_WRONLY);
pid_printf("The client is ready,Enter message(Ctrl+D to exit).\n");
while (fgets(buf,sizeof(buf),stdin)!= NULL)
{
write(fd,buf,strlen(buf));
}
pid_printf("Client exiting.\n");
close(fd);
}
int main(int argc,char *argv[])
{
if(argc < 2)
{
server();
}
else
{
client(argv);
}
}
//在运行第二个终端时,无法达到预期的进程通信