写入子进程的字符串已损坏?

时间:2015-08-05 13:04:02

标签: c++ pipe fork

我想在子进程中执行程序。当程序直接在终端中运行时,程序会起作用:它等待一些输入,并且在处理之前必须发送Control + D / EOF。

在我下面的代码中,程序似乎没有正确接收到字符串,看起来它只是看到某些部分或者什么都没有,当它收到EOF时,即使我只发送一次,它似乎也会发生几次。

如果有人能告诉我这里出了什么问题?

    int main(int argc, char** argv) {
      int pipes[2][2]; //pipe[0] read, pipe[1] write

      #define PARENT_READ_FD  ( pipes[1][0] )
      #define PARENT_WRITE_FD ( pipes[0][1] )

      #define CHILD_READ_FD   ( pipes[0][0]  )
      #define CHILD_WRITE_FD  ( pipes[1][1]  )

      // pipes for parent to write and read
      assert( (pipe(pipes[1])) == 0 );
      assert( (pipe(pipes[0])) == 0 );

      int pid = fork();
      if(pid == 0) {
          char *argv[]={"/workspace/osm/overpass/osm3s_v0.7.51/bin/osm3s_query", "--db-dir=$DB_DIR"};

          assert( (dup2(CHILD_READ_FD, STDIN_FILENO)) != -1);
          assert( (dup2(CHILD_WRITE_FD, STDOUT_FILENO)) != -1);

          close(CHILD_READ_FD);
          close(CHILD_WRITE_FD);
          close(PARENT_READ_FD);
          close(PARENT_WRITE_FD);

          execv(argv[0], argv);
      } else if(pid > 0) {
          char buffer[1000];
          int count;

          close(CHILD_READ_FD);
          close(CHILD_WRITE_FD);

          int query_size = strlen(query.c_str()) + 1;
          int succesful_write = write(PARENT_WRITE_FD, &query, query_size);
          assert(succesful_write==query_size);
          close(PARENT_WRITE_FD);

          // Read from child’s stdout
          while( count = read(PARENT_READ_FD, buffer, sizeof(buffer)-1) > 0){
            cerr << buffer << endl;
          }
      } else {
        cerr << "Could not fork child process" << endl;
        exit(EXIT_FAILURE);
      }
    }

例如,程序输出的错误(每次运行程序时都会改变):

    line 1: parse error: Unknown type "�"
    line 1: parse error: An empty query is not allowed
    line 1: parse error: Unknown type "n"
    line 1: parse error: An empty query is not allowed
    line 1: parse error: Unknown type "�"
    ...

0 个答案:

没有答案