简体   繁体   中英

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. 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. The one you're writing into has nobody reading it, and the one you're reading from had nothing written to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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