Question

Operating system C language question: How to use pipes and file descriptors in Linux C? I...

Operating system C language question:

How to use pipes and file descriptors in Linux C? I don't understand why people can use 1 newly created array int fd[2] and then they can communicate with each others..

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have written a program to demonstrate how pipe and fd are used.

you can go through the code and the comments.

Program:

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

int main(void)
{
        int     fd[2];       //for storing file descriptors given by pipe()
       pid_t pid;           //for storing pid returned by pid
      
        pipe(fd);           //creating pipe
      
        pid = fork();        //creating child
      
        if( pid == -1)
        {
                perror("fork failed");
                exit(1);
        }
      
       /*the semantics of fork is that,
       whole data is copied from parent to child
       this means that fd[2], pid can be used by both
       parent and child */
      
       //if child
        if(pid == 0)
        {
                /* Child process close it's input side fd[0]
                   which it has */
                close(fd[0]);

                /* write the string to it's output side fd[1] */
                write(fd[1], "Hello I'm Child", 16);
                exit(0);
        }
        //if parent
        else
        {
           char buffer[20];
                /* Parent process closes it's output side fd[1] */
                close(fd[1]);

                /* Read string from it's input side */
                read(fd[0], buffer, sizeof(buffer));
                printf("\nReceived from Child: %s\n\n", buffer);
        }
        return(0);
}

Execution and Output:

Add a comment
Know the answer?
Add Answer to:
Operating system C language question: How to use pipes and file descriptors in Linux C? I...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT