如何使用IPC与子进程正确通信?

时间:2017-08-04 08:51:35

标签: c ipc

我正在尝试创建几个子进程来处理来自父进程的'命令'并返回结果。为此,我正在使用并跟踪每个流程的管道。

然而,我似乎无法使它们正常工作。这是一个1父母和1个孩子的小片段。我将“abc”作为第二个有效载荷而不是“xyz123”。

#include<stdio.h>
#include<unistd.h>
#include<string.h>

int main() {
  int cmd_pipe[2];
  int msg_pipe[2];
  int len_pipe[2];
  if (pipe(cmd_pipe) < 0) {
    printf("\nCMD Pipe error!\n");
  };
  if (pipe(msg_pipe) < 0) {
    printf("\nMSG Pipe error!\n");
  };
  if (pipe(len_pipe) < 0) {
    printf("\nLEN Pipe error!\n");
  };
  if (fork() == 0) {
    // child
    int command;
    char buffer[10];
    while(1) {
      printf("\nChild process waiting for command.\n");
      read(cmd_pipe[0], &command, sizeof(command)); // will block until it gets something
      if (command == 5) {
        char* payload1 = "abc";
        size_t payload1_len = strlen(payload1);
        write(len_pipe[1], &payload1_len, sizeof(payload1_len));
        write(msg_pipe[1], payload1, payload1_len);
      }
      if (command == 2) {
        char* payload2 = "xyz123";
        size_t payload2_len = strlen(payload2);
        write(len_pipe[1], &payload2_len, sizeof(payload2_len));
        write(msg_pipe[1], payload2, payload2_len);
      }
    }
  } else {
    // parent
    sleep(2); // wait for child
    int cmd = 5;
    printf("\nSending command %d to child\n", cmd);
    write(cmd_pipe[1], &cmd, sizeof(cmd));
    int length;
    read(len_pipe[0], &length, sizeof(length)); // length of payload
    char payload[length];
    read(msg_pipe[0], payload, length);
    printf("\nGot payload: %s\n", payload); // %s would be "abc" here.

    cmd = 2;
    printf("\nSending command %d to child\n", cmd);
    write(cmd_pipe[1], &cmd, sizeof(cmd));
    read(len_pipe[0], &length, sizeof(length)); // length of payload
    char payload2[length];
    read(msg_pipe[0], payload2, length);
    printf("\nGot second payload: %s\n", payload2); // %s should be "xyz123" here but it's still abc
  }
  return 0;
}

0 个答案:

没有答案