Communicate with multiple process using named pipe


 
Thread Tools Search this Thread
Top Forums Programming Communicate with multiple process using named pipe
# 1  
Old 11-17-2011
processs and pipe

how to read and write on pipes to communicate with each other?

Last edited by nimesh; 11-18-2011 at 03:29 PM..
# 2  
Old 11-17-2011
Create two named pipes with mkfifo("pipename", 0660);

Open them with
Code:
int readfd=open("pipename", O_RDONLY);

Code:
int writefd=open("pipename", O_WRONLY);

Be sure to open them in the same order in both processes. When you open the pipe for read in one, it will wait for the other process to open it for write before finishing.

Write to it with write(fd, buffer, size), read from it with read(fd, buffer, size)
# 3  
Old 11-18-2011
Thank you for the help. But i have another issue now.

I open a FIFO to write
Code:
mkfifo ("pipe1", 0777);
int writefd = open ("pipe1", O_WRONLY);

now how do I write argv[1] to pipe1?
I did:
Code:
   write (writefd, argv[1], BUF_PIPE);

when I run my program with an argument, it doesnt do anything. I have to hit ctrl+C to stop.

Any help!!

Last edited by vbe; 11-18-2011 at 11:05 AM.. Reason: Use code tags for your code!!!!
# 4  
Old 11-18-2011
0777 gives the entire world read, write, and execute permissions to your fifo, and it doesn't even make sense to execute a fifo. I suggest you try the permissions I suggested, 0660, a better generic number than 777.

Quote:
now how do I write argv[1] to pipe1?
I did:
write (writefd, argv[1], BUF_PIPE);
What in the world is BUF_PIPE? I can't find it in any include files.

argv[1] can vary in length, yes? If you don't have BUF_PIPE bytes in argv[1], you shouldn't use BUF_PIPE bytes from it. That would go beyond the end of the string and either send garbage or crash. (Or if BUF_PIPE is less, it'd only send part of the string.)

Since it's an ordinary NULL-terminated string, we can use strlen() to measure how long it is.

Code:
// for strlen
#include <string.h>

...

if(argc < 2)
{
        fprintf(stderr, "Not enough arguments");
        return(1);
}

char c='\n';
write(writefd, argv[1], strlen(argv[1]));
// You might need a newline for the pipe to flush
write(writefd, &c, 1);

Also remember that, like I said, named pipes wait for the other side to open them. If the other half of your program isn't going, it will wait for it. This is normal.

Also remember that, because of that, if you open the pipes in the wrong order, they will still wait for each other forever even when you run both. If they both try to open their own write-ends without the other process opening the read-end first, they'll be stuck.

All of this is only a guess because you didn't actually post your program, please do.
# 5  
Old 11-18-2011
I am sorry, I meant to write PIPE_BUF instead of BUF_PIPE. and PIPE_BUF is in limits.h
Anyway, I am still not getting it. Here is all my scratch work

This is progA.c. progA gets an integer from argv[1] and writes it to pipe1. That progB reads.
Code:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char* argv [])
{
int readfd, writefd;
char buffer [100];

if (argc != 2)
   printf ("Invalid number of argument. Enter an integer\n");
else
   {
   if (access ("pipe1", F_OK) == -1)   //if pipe1 cannot be accessed
      {
      int res = mkfifo ("pipe1", 0660);
      if (res != 0)
         printf ("ERROR: Pipe cannot be created\n");
    else;
      }
   }

writefd = open ("pipe1", O_WRONLY);
write (writefd, &argv[1], PIPE_BUF);

close (writefd);
return (0);
}

And here is progB that reads integer from pipe1, if positive integer then adds 10 to it and writes it to pipe2. And progA has to read pipe2.
ProgB
Code:
 #include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>

int main ()
{
int readfd;
char buffer [100];
//mkfifo ("pipe2", 0660);
readfd = open ("pipe1", O_RDONLY);
read (readfd, buffer, PIPE_BUF);
printf ("Buffer has %d\n", buffer);
return 0;
}

In my scratch work all I am trying to do is progA reads integer from argv[1], write it to pipe1 and pipe1 is read by progB and prints. So that I can understand the concept better.

I am looking at a lot of resources online and in my book but I cant put everything together. And how do I execute my programs?

thank you so much for all your help!

Last edited by nimesh; 11-18-2011 at 03:42 PM..
# 6  
Old 11-18-2011
Both programs have to run at the same time.

Code:
./writer & # Run script1 in the background
./reader # Run reader in the foreground
wait # wait for writer to finish

Lots of errors in your code that I'll get to in a minute.

---------- Post updated at 11:30 AM ---------- Previous update was at 11:14 AM ----------

Code:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h> // For strlen
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char* argv [])
{
        int readfd, writefd;
        // If you're going to read PIPE_BUF bytes, you might as well have
        // a buffer big enough to hold PIPE_BUF bytes.
        // Otherwise, if you ever read more than 100, it'll crash!
        char buffer [PIPE_BUF];

        if(argc != 2)
        {
                // Error messages belong on standard error.
                fprintf (stderr, "Invalid number of argument. Enter an integer\n");

                // Instead of chaining if/else 99 deep, 
                // quit the program early.
                return(1);
        }

        // Good idea!
        if (access ("pipe1", F_OK) == -1)   //if pipe1 cannot be accessed
       {
                int res = mkfifo ("pipe1", 0660);
                if (res != 0)
                {
                        Error messages belong on standard error.
                        fprintf (stderr, "ERROR: Pipe cannot be created\n");
                        // Instead of chaining if/else 99 deep, 
                        // quit the program early.
                        return(1);

                }
        }

        writefd = open ("pipe1", O_WRONLY);

        //argv[1] is already a pointer, no need to take its address.
        // Don't write PIPE_BUF bytes unless you actually have PIPE_BUF bytes!
        // The string is exactly strlen() bytes long.
        //write (writefd, &argv[1], PIPE_BUF);
        write(writefd, argv[1], strlen(argv[1]));

        close (writefd);

        return (0);
}


Code:
 #include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>

int main ()
{
        int readfd, value;
        ssize_t bytes;
        // If you're going to read PIPE_BUF bytes, you might as well have
        // a buffer big enough to hold PIPE_BUF bytes.
        // Otherwise, if you ever read more than 100, it'll crash!
        char buffer [PIPE_BUF];

        //mkfifo ("pipe2", 0660);

        readfd = open ("pipe1", O_RDONLY);
        bytes=read (readfd, buffer, PIPE_BUF);

        fprintf(stderr, "Read %d bytes\n", (int)bytes);

        // Put a NULL terminator on the end so printf/strlen/etc won't crash.
        buffer[bytes]='\0';        

        // buffer is a character array, not an integer.
        // You can't do math on it until you convert it.
        printf ("Buffer has %s\n", buffer);

        if(sscanf(buffer, "%d", &value) != 1)
        {
                fprintf(stderr, "string '%s' is not a number\n", buffer);
                return(1);
        }

        printf("value is %d\n", value);

        // convert back into a string
        sprintf(buffer, "%d", value+10);

        printf("buffer is now %s\n", buffer);
        close(readfd);
        return 0;
}


Last edited by Corona688; 11-18-2011 at 01:37 PM..
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

Named pipe hanging?

Ok, I can't seem to figure this out or find anything on the web about this. I'm on Sun Solaris, UNIX. I have the following test script: #!/bin/ksh touch test.file LOG=./tmp.log rm -f ${LOG} PIPE=./tmp.pipe mkfifo ${PIPE} trap "rm -f ${PIPE}" EXIT tee -a ${LOG} < ${PIPE} & ... (17 Replies)
Discussion started by: Ditto
17 Replies

2. Shell Programming and Scripting

Named pipe performance

Hi, I am getting data into a Named pipe. Does Named pipe have any size restriction; I know it does not have any storage and it just passes on the data to the next process. I want to know, if there will be a difference in the Named pipe performance if the data input is more. (I am using DB2... (1 Reply)
Discussion started by: sudvishw
1 Replies

3. Shell Programming and Scripting

Using Named pipe in shell script

Hi, I want to use a Named pipe to get input from a growing file for further processing. When I prototype this scenario using a while loop, the data is not written to the named pipe. This the script I use to get data into the Named pipe: #!/bin/ksh mkfifo pipe while (( n <= 10 )) do echo... (2 Replies)
Discussion started by: sudvishw
2 Replies

4. Shell Programming and Scripting

pipe to file named with date

I would like to pipe (redirect ? - what is the right term?) the output of my script to a file named with the current date. If I run this at a command prompt: date +'%Y%m%d" ...it returns "20110429" OK, that's good... so I try: ./script.sh > "'date +%Y%m%d'.csv" I get a file... (1 Reply)
Discussion started by: landog
1 Replies

5. UNIX for Advanced & Expert Users

will a named pipe always be size 0 on filesystem?

I did cat < myFile >> myPipe I was hoping that if I did ls -l, myPipe would now be holding the contents of myFile, and would be the same size. But it was 0. Also strange was that when I did the command above, cat did not return control back to the shell. Why? thanks (4 Replies)
Discussion started by: JamesByars
4 Replies

6. UNIX for Dummies Questions & Answers

Named Pipe contents to a file

I want to copy the contents of a named pipe to a file. I have tried using: cat pipe.p >> transcript.log but I have been unsuccessful, any ideas? (4 Replies)
Discussion started by: carl_vieyra
4 Replies

7. UNIX for Dummies Questions & Answers

Named PIPE

Gurus, I've a File Transaction Server, which communicates with other servers and performs some processing.It uses many Named PIPE's. By mistake i copied a named PIPE into a text file. I heard that PIPE files shouldn't be copied.Isn't it? Since it's a production box, i'm afraid on... (2 Replies)
Discussion started by: Tamil
2 Replies

8. UNIX for Advanced & Expert Users

named pipe with persistent buffer

Hey folks, i need communicate between 2 processes in a reliable manner. The information delivery has to be guarenteed. I thought about proc 2 sending a signal to proc 1 when information has being written to disc and wirte() has been verified (sync/flush). The IPC method for the data is named... (4 Replies)
Discussion started by: heck
4 Replies

9. Programming

IPC using named pipe

Hi All, I am facing a vague issue while trying to make two process talk to each other using named pipe. read process ========= The process which reads, basically creates FIFO using mkfifo - ret_val = mkfifo(HALF_DUPLEX, 0666) func. It then opens the pipe using open func - fd = open... (2 Replies)
Discussion started by: sharanbr
2 Replies

10. UNIX for Advanced & Expert Users

IPC using named pipe

Hi All, I am facing a vague issue while trying to make two process talk to each other using named pipe. read process ========= The process which reads, basically creates FIFO using mkfifo - ret_val = mkfifo(HALF_DUPLEX, 0666);) func. It then opens the pipe using open func - fd =... (1 Reply)
Discussion started by: sharanbr
1 Replies
Login or Register to Ask a Question