LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 804|回复: 4

看一下这个程序

[复制链接]
发表于 2006-3-30 00:36:12 | 显示全部楼层 |阅读模式
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
void quit(char *buf)
{
  perror(buf);
  exit(EXIT_FAILURE);
}
int main()
{
  int fd;
  time_t tp;
  fd=mkfifo("fi",0644);
  if(fd<0)
    quit("mkfifo");
  int pid=fork();
  if(pid<0)
    quit("fork");
  else if(pid>0)
  {
    if((open("fi",O_RDONLY|O_NONBLOCK,0644))<0)
      quit("child open");
    char buf[PIPE_BUF-1];
    int i=read(fd,buf,PIPE_BUF-1);
    if(i>0)
      printf("child read : %s",buf);
  }
  else
  {
    if((open("fi",O_WRONLY,0644))<0)
      quit("child open");
    char buf1[PIPE_BUF-1];
    int j=sprintf(buf1,"%d send %s",getpid(),ctime(&tp));
    write(fd,buf1,j+1);
  }
  close(fd);
  exit(EXIT_SUCCESS);
}
我想实现两个进程同时对命名管道读写,应如何修改,现在这个程序已运行,就不动了 只能ctrl+c终止
发表于 2006-3-30 11:51:27 | 显示全部楼层
你的fd没有赋值。改过的程序:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/types.h>
  4. #include <sys/stat.h>
  5. #include <errno.h>
  6. #include <fcntl.h>
  7. #include <limits.h>

  8. void quit(char *buf)
  9. {
  10.     perror(buf);
  11.     exit(EXIT_FAILURE);
  12. }

  13. int main()
  14. {
  15.     int fd;
  16.     time_t tp;
  17.     fd=mkfifo("fi",0644);
  18.     if(fd<0)
  19.         quit("mkfifo");
  20.     int pid=fork();
  21.     if(pid<0)
  22.         quit("fork");
  23.     else if(pid>0)
  24.     {
  25.         if((fd = open("fi",O_RDONLY,0644))<0)
  26.             quit("parent open");
  27.         char buf[PIPE_BUF-1];
  28.         int i=read(fd,buf,PIPE_BUF-1);
  29.         if(i>0)
  30.             printf("parent read : %s",buf);
  31.     }
  32.     else
  33.     {
  34.         if((fd = open("fi",O_WRONLY,0644))<0)
  35.             quit("child open");
  36.         char buf1[PIPE_BUF-1];
  37.         int j=sprintf(buf1,"%d send %s",getpid(),ctime(&tp));
  38.         write(fd,buf1,j+1);
  39.     }
  40.     close(fd);
  41.     exit(EXIT_SUCCESS);
  42. }

复制代码
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-3-31 21:10:09 | 显示全部楼层
还是不对啊,改后还是和以前一个问题,就是程序执行时就不动了
回复 支持 反对

使用道具 举报

发表于 2006-3-31 21:31:21 | 显示全部楼层
Post by zcw_ease
还是不对啊,改后还是和以前一个问题,就是程序执行时就不动了


make sure u have carefully read what aliff said and his program
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-3-31 22:03:14 | 显示全部楼层
惭愧惭愧,my fault
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表