Saturday, January 17, 2015

IPC: message passing through pipe

simple pipe ipc:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>

int main(void)
{
    int pfds[2];
    char buf[30];

    if (pipe(pfds) == -1) {
        perror("pipe");
        exit(1);
    }

    printf("writing to file descriptor #%d\n", pfds[1]);
    write(pfds[1], "test", 5);
    printf("reading from file descriptor #%d\n", pfds[0]);
    read(pfds[0], buf, 5);
    printf("read \"%s\"\n", buf);

    return 0;
}

example 2:

#include<stdio.h>
#include<stdlib.h>
#include<wait.h>
#include<unistd.h>
main()
{
    int pfd[2],retval=1,status;
    char buf1[]="hi selvakumar";
    char buf2[30]={0};
    pid_t pid;
    pipe(pfd);
    pid=fork();
    switch(pid)
    {
        case -1:
            printf("\n failing in the process creation");
            break;
        case 0:
            printf("\n in child process \n");
            write(pfd[1],buf1,sizeof(buf1));
            exit(retval);
            break;
        default:
            printf("\n in parent process \n");
            printf("\n waiting for the child process to complete \n");
            read(pfd[0],buf2,sizeof(buf2));
            printf("\n information from the child process:\t%s\n",buf2);
            wait(&status);

    }
}

Message passing through pipe

/*
Name        :   Message passing through pipe
Author      :   jishnu7
Web         :   http://thecodecracker.com
Date        :   25-Sep-2010
Description :   C Program to implement message
                passing between processes using pipe
License     :   GNU GPL License
*/

#include<stdio.h>
#include<unistd.h>


int main()
{
    int f[2],count,i;
    char a[20];
        
    pipe(f);
    i = fork();
    if(i==0)
    {  
        read(f[0],a,sizeof(a));
        printf("-------------\nChild process\n-------------\n");
        printf("Message from parent : \"%s\"\n",a);
        printf("Message to patent process : ");
        scanf("%s",a);
        write(f[1],a,sizeof(a));
    }  
    else
    {  
        printf("--------------\nParent Process\n--------------\n");
        printf("Enter the message to child process : ");
        scanf("%s",a);
        write(f[1],a,sizeof(a));
        sleep(1);
        read(f[0],a,sizeof(a));
        printf("--------------\nParent Process\n--------------\n");
        printf("Message from child : \"%s\"\n",a);
    }
}


OUTPUT
--------------
Parent Process
--------------
Enter the message to child process : hello
-------------
Child process
-------------
Message from parent : "hello"
Message to patent process : hai
--------------
Parent Process
--------------
Message from child : "hai" 
 
 
reference:
http://beej.us/guide/bgipc/output/html/multipage/pipes.html
https://linuxprograms.wordpress.com/2008/01/23/using-pipes-in-linux-programming/ 
 

No comments:

Post a Comment