我想fork一个孩子和管道连接到标准输入和孩子的标准输出。然后运行exec ./xx。之后,我从父母给孩子送17,孩子打印它。迄今为止都很好。但是当我向父母发送回复时,它不起作用。 结果是:输出什么,看起来像等待一些输入。 如果我删除代码“fscanf(b,”%d“,& x);”在父母,输出是: 从C 0从p 17 我很困惑,为什么我得到奇怪的结果?谢谢Linux下C从孩子将数据发送到家长是好的,但不能从孩子将数据发送到父
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
int main(int argc, char** argv) {
int fds[2], cp[2], x = 0;
pipe(fds);
pipe(cp);
int pid=fork();
// c
if (pid==0) {
close(fds[1]);
close(cp[0]);
dup2(fds[0],0);
dup2(cp[1], 1);
close(cp[1]);
close(fds[0]);
execlp("./xx", "xx", 0);
}
// p
if (pid) {
close(fds[0]);
close(cp[1]);
dup2(fds[1],1);
close(fds[1]);
FILE* a=fdopen(1, "w");
FILE* b=fdopen(cp[0], "r");
fprintf(a, "17");
fscanf(b, "%d", &x);
fprintf(stderr, "from C %d", x);
}
return 0;
}
XX
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
int main() {
int y = 0;
FILE* r=fdopen(STDIN_FILENO, "r");
fscanf(r, "%d", &y);
fprintf(stderr, "from p %d \n ", y);
FILE* w=fdopen(STDOUT_FILENO, "w");
fprintf(w, "17");
return 0;
}
你试图用写函数,而不是fprintf中? '写(STDOUT_FILENO, “17”,2)' – krystian71115
你为什么CP [1]'DUP2后'关'(CP [1],1)' – krystian71115
我的老师告诉我们一个管道只有写,另一个入口为了阅读,我们必须关闭它。 –