繁体   English   中英

带有命名管道的C语言管理器

[英]IPC in C with named pipes

我试图在C中创建两个程序(A和B).A向B发送一个char数组,B将另一个char放在他从A接收到的char数组中并将其发送回A.之后A得到了改进的char数组他会打印出来的。

问题是,我不知道如何告诉A,当他从B收到改进的char数组时,它应该首先打印它

有人可以帮忙吗?

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

int main() {
        // Here we use A and B as parent and child, made by fork
        // This allows us to pass pipe FDs
        int inpipe[2];
        int outpipe[2];
        pipe(inpipe);
        pipe(outpipe);
        const int arr_len = 4;
        const char buf[arr_len] = "ABD"; // Character [3] is implicit NUL
        int x = fork();
        if(x == -1) {
                perror("Fork error");
        }
        if(x == 0) {
                // Child
                char my_buf[arr_len];
                read(inpipe[0], my_buf, arr_len);
                // Improve it
                my_buf[2] = 'C'; // ABC looks better than ABD
                // Send it back
                write(outpipe[1], my_buf, arr_len);
                exit(0);
        }
        char my_buf[4];
        write(inpipe[1], buf, arr_len);
        // Will lock waiting for data
        read(outpipe[0], my_buf, arr_len);
        // Close pipes
        close(inpipe[0]);
        close(inpipe[1]);
        close(outpipe[0]);
        close(outpipe[1]);
        // Dump it
        printf("%s\n", my_buf);
        return 0;
}

尝试运行此示例,并看到它在两个进程之间发送数组。 如果一个人不分叉,唯一的问题是使用命名管道(用mkfifo调用替换pipe调用,以及其他一些更改)。 随意基于这个例子。 还看看这个:

int ifd = mypipe[0], ofd = mypipe[1]; // mypipe is got somewhere before
FILE *istream = fdopen(ifd, "r"), ostream = fdopen(ofd, "w");
// Now use any stdio functions on istream and ostream

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM