命名管道函数FIFO编写错误

wangbylove 2011-08-04 06:49:26
#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);
}
}

//在运行第二个终端时,无法达到预期的进程通信
...全文
35 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
DIE654456 2011-08-05
  • 打赏
  • 举报
回复
unlink(FIFO_PATH);去掉,
注意在每次系统调用之后执行perror检查,比如read的失败,write也会失败

69,370

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧