C中进程之间的管道数据问题

时间:2017-12-08 21:41:45

标签: c pipe stdout stdin dup

我需要从读取函数传递到写入函数。我使用命令行./mapstore retrieve ABCD 2>/dev/null | ./mapstore -p ./new_dir/ stream ABCD进行了测试,这成功地将数据写入管道并成功读取管道中的数据并将其写入文件系统。

我想在C中这样做,但我遇到了问题。 retrieve_data failed: Undefined error: 0我的代码基于此问题Classic C. Using pipes in execvp function, stdin and stdout redirection

#include <unistd.h>
#include <stdlib.h>
#include "mapstore.h"

int main(int argc, char *argv[]) {

    mapstore_ctx ctx;
    if (initialize_mapstore(ctx, NULL) != 0) {
       fprintf(stderr, "Error initializing mapstore\n");
        return 1;
    }

    mapstore_ctx new_ctx;
    if (initialize_mapstore(&new_ctx, NULL) != 0) {
       fprintf(stderr, "Error initializing mapstore\n");
        return 1;
    }

    char *hash = argv[1];
    int des_p[2];
    if(pipe(des_p) == -1) {
      fprintf(stderr, "Failed to create pipe\n");
      status = 1;
      goto end_restructure;
    }
    printf("1\n");

    if(fork() == 0) {
        printf("1a\n");
        close(des_p[0]);       //closing pipe read
        printf("2a\n");
        close(des_p[1]);
        printf("3a\n");
        if ((status = retrieve_data(ctx, des_p[1], hashes[i])) != 0) {
            perror("retrieve_data failed");
            exit(1);
        }
        printf("4a\n");
        exit(0);
    }

    if(fork() == 0) {
        printf("1b\n");
        close(des_p[1]);       //closing pipe write
        printf("2b\n");
        close(des_p[0]);
        printf("3b\n");
        if ((status = store_data(&new_ctx, des_p[0], hashes[i])) != 0) {
            perror("store_data failed");
            exit(1);
        }
        printf("4b\n");
        exit(0);
    }
    printf("2\n");
    close(des_p[0]);
    printf("3\n");
    close(des_p[1]);
    printf("4\n");
    wait(0);
    wait(0);
    return 0;
}

此处提供完整代码https://github.com/aleitner/libmapstore/blob/master/src/mapstore.c#L374

0 个答案:

没有答案