命名管道导致无限循环/无输出

时间:2016-01-08 11:47:53

标签: c macos pipe ipc named-pipes

我一直在尝试创建一个使用命名管道在进程之间进行通信的简单程序。我已尝试在OS X Yosemite和Ubuntu Linux 14.04(在Parallels上虚拟化)上执行此操作,下面是应该有3个进程通过相同命名管道进行通信的程序的代码

我的代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

void proc1(char *named_pipe) {

  printf("Proc 1\n");

  int fd;
  char *mess1;

  mess1 = "Message from \"proc1\".";
  fd = open(named_pipe, O_WRONLY);
  if(fd == -1) {
    printf("error : opening\n");
    exit(-1);
  }
  printf("Opened\n");
  if(write(fd, mess1, sizeof(mess1)) == -1) {
    perror("error : writing\n");
    exit(-1);
  }
  close(fd);

  printf("End of Process 1.\n");

}

void proc2(char *named_pipe) {

  int fd;
  char buf[50];
  char *mess2;

  fd = open(named_pipe, O_RDONLY);
  read(fd, buf, 50);
  printf("Received : %s\n", buf);
  close(fd);

  mess2 = "Message from \"proc2\".";
  fd = open(named_pipe, O_WRONLY);
  write(fd, mess2, sizeof(mess2));
  close(fd);

  printf("End of Process 2.\n");

}

void proc3(char *named_pipe) {

  int fd;
  char buf[50];

  fd = open(named_pipe, O_RDONLY);
  read(fd, buf, 50);
  printf("Received : %s\n", buf);
  close(fd);

  printf("End of Process 3.\n");

}

int main() {

  char tube[4] = "tube";

  printf("### Start of program ###\n");

  if(mkfifo(tube, 0600) == -1) {
    perror("Problem creating named pipe.\n");
    exit(99);
  }

  proc1(tube);
  proc2(tube);
  proc3(tube);

  printf("### End of program ###\n");

  return 0;
}

我的输出

### Start of program ###
Proc 1

然后没有任何反应,除了光标闪烁表示(?)程序仍在运行。因此,每次运行此程序时,代码似乎无限循环,而没有告诉我原因。

我的问题

真正让我感到困惑的是,即使是我在本网站上发现的经过验证的工作代码,同时研究此问题导致相同的无限循环/无输出; see that code here。这可能是我操作系统的问题吗?请记住,在OSX和Ubuntu上都会出现完全相同的结果。

更新

解决方案

(感谢@Sami Kuhmonen)

我需要同时运行2个程序(来自链接代码)。现在觉得有点傻!

0 个答案:

没有答案