简体   繁体   English

Linux IPC管道无法正常工作

[英]Linux IPC pipe is not working

so I am new to inter-process communications and processes in linux, so I really cannot figure out what the problem is. 所以我不熟悉linux中的进程间通信和进程,所以我真的无法弄清楚问题是什么。 The following program I wrote is the same problem I am having on a homework assignment consisting of using pipes condensed down. 我编写的以下程序与我在家庭作业中使用的问题相同,包括使用缩减的管道。 It is basically sending one character from the child to the parent, but it does not print out the character. 它基本上是从孩子发送一个字符到父母,但它不会打印出该字符。
it print out: 它打印出来:

hello from child
sending a
hello from parent
trying to receive...
received: reaping child

where on the third line it should say 它应该说在第三行的哪个位置

received: a

Any answers are appreciated, and also if you have any helpful criticism of anything else in the program. 任何答案都表示赞赏,如果您对该计划中的任何其他内容有任何有用的批评。 Thanks everyone 感谢大家

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


int main(int argc, char* argv[])
{
    pid_t pid = fork();
    int comm[2];

    pipe(comm);

if (pid == 0)
{
    char send = 'a';
    int check;
    close(comm[0]);
    printf("hello from child\n");
    printf("sending %c\n", send);
    check =  write(comm[1], &send, 1);
    printf("%d\n", check);
    exit(1);
}
else if (pid > 0)
{
    char get = ' ';
    int check;
    close(comm[1]);
    printf("hello from parent\n");
    printf("trying to receive...\n");
    read(comm[0], &get, 2);
    printf("received: %c\n", get);
    printf("reaping child\n");
    wait(NULL);
    return 0;
}

return 0;

}

You got the pipe and the fork in the wrong order! 你的管子和叉子的顺序错了! Your process forks, then both processes call pipe, so 2 separate pipes are being created. 您的进程分叉,然后两个进程都调用管道,因此正在创建2个单独的管道。 The one you're writing into has nobody reading it, and the one you're reading from had nothing written to it. 你写的那个人没有人读它,而你正在读的那个没有写任何东西。

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

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