2015-09-18 29 views
-1

我想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; 
} 
+0

你试图用写函数,而不是fprintf中? '写(STDOUT_FILENO, “17”,2)' – krystian71115

+0

你为什么CP [1]'DUP2后'关'(CP [1],1)' – krystian71115

+0

我的老师告诉我们一个管道只有写,另一个入口为了阅读,我们必须关闭它。 –

回答

0

使用此代码:

#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(); 

if (pid==0) {    
    close(fds[1]); 
    close(cp[0]); 
    dup2(fds[0], 0); 
    dup2(cp[1], 1);  
    execlp("./xx", "xx", NULL);  
} 
if (pid > 0) {  

    close(fds[0]); 
    close(cp[1]); 
    FILE * a = fdopen(fds[1], "w"); 
    FILE * b = fdopen(cp[0], "r"); 
    fprintf(a, "17\n"); 
    fflush(a); 
    fscanf(b, "%d", &x); 
    fprintf(stderr, "from C %d\n", x); 
} else { 
    // error while fork 
    perror("fork"); // print error to console. 
    return 1; 
} 

    return 0; 
} 

及××:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
#include <stdbool.h> 
int main() { 
    int y = 0; 
    FILE* r = stdin; 
    fscanf(r, "%d", &y); 
    fprintf(stderr, "from p %d \n ", y); 
    FILE* w = stdout; 
    fprintf(w, "17\n"); 
    fflush(w); 
    return 0; 
} 

它的工作对我来说:)

1

我想我想通了。你需要刷新你的输出缓冲区。对于stderr,fprintf仅默认执行此操作。所以在parent.c文件:

fprintf(a, "17"); 
fflush(a); 

而且在孩子:

fprintf(w, "17"); 
fflush(w); 

我早就预料到了自己的工作,但我不是一个C专家,它没“T。但是,将父代中的两条线更改为

fprintf(a, "17\n"); 
fflush(a); 

使它适用于我。

+0

谢谢你的帮助,我试试你的想法,但得到相同的结果。 –

+0

什么版本(发行版)的Linux您使用的是? –

+0

我不知道由学校提供服务的系统,我只是用苔藓来遥控它 –

相关问题