C库之pipe和fdopen

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

int main(int argc, char* argv[])
{
    int shell_to_app[2] = {0};
    int app_to_shell[2] = {0};

    pipe(shell_to_app);
    pipe(app_to_shell);

    if(fork() == 0)
    {
        close(shell_to_app[1]);
        close(app_to_shell[0]);

        dup2(shell_to_app[0], STDIN_FILENO);
        dup2(app_to_shell[1], STDOUT_FILENO);

        execl("./app.exe", "./app.exe", NULL);
    }
    else
    {
        int i = 0;
        FILE* in = fdopen(app_to_shell[0], "r");
        FILE* out = fdopen(shell_to_app[1], "w");

        char message[256] = {0};
        close(shell_to_app[0]);
        close(app_to_shell[1]);

                fgets(message, sizeof(message), in);
        printf("1: %s\n", message);
        fprintf(out, "1234\n");
        fflush(out);
                fgets(message, sizeof(message), in);
        printf("2: %s\n",  message);
                fclose(in);
                fclose(out);
    }

    return 0;
}


发布了73 篇原创文章 · 获赞 13 · 访问量 25万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览