我试图在C中创建两个程序(A和B).A向B发送一个char数组,B将另一个char放入他从A收到的char数组中并将其发送回A.之后得到了改进来自B的char数组他将打印出来。
问题是,我不知道怎么告诉A,当他从B收到改进的char数组时应该首先打印它
有人可以帮忙吗?
答案 0 :(得分:0)
#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;
}
尝试运行此示例,并看到它在两个进程之间发送数组。如果一个人没有分叉,唯一的问题是使用命名管道(用pipe
调用替换mkfifo
调用,以及其他一些更改)。随意基于这个例子。另外看看:
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