Domanda

Reader Side,

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
        int fd;
        char buff[100];
        fd = open ("MyPipes",O_RDONLY);
        read (fd, buff, 100);
        printf ("%s\n",buff);
        close(fd);
}

Writer Side,

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

char *ptr = "Akshit Soni";
int main()
{
        int fd;
        fd = open ("MyPipes",O_WRONLY);
        write (fd, ptr, strlen(ptr));
        close (fd);
}

Problem is that reader program outputs gets garbage value.

È stato utile?

Soluzione

Your (first) problem lies here:

write (fd, ptr, strlen(ptr));

The strlen of "Akshit Soni" does not include the trailing NUL character. You need to use strlen (ptr) + 1 as the length.

You should also allow for the fact that read() may not return all the bytes you asked for (100) nor all the bytes that were sent (12 including the NUL). It's possible (for reasons such as timing or interrupts) that only part of the data may be read by a single call to read().

To allow for that, you could try something like:

int main()
{
    int fd;
    char buff[100];
    fd = open ("MyPipes",O_RDONLY);
    int sz = read (fd, buff, 100);
    while ((sz > 0) && (buff[sz-1] != '\0')) {
        printf ("%*.*s", sz-1, sz-1, buff);
        sz = read (fd, buff, 100);
    }
    if (sz > 0)
        printf ("%s\n",buff);
    close(fd);
}

As an aside, make sure you have actually created the named pipe before you run the code, with something like (from bash):

mkfifo MyPipes

Altri suggerimenti

Make sure that you open things in the right order; first open the pipe for write, then for read. You don't test that you don't have a NULL response to the opening of the pipe, and you may well be looking at garbage. Always test the return value of your functions...

  1. it is not correct to create named pipe. use mkfifo to create it

  2. for create file, might need to use more flags, assuming there is no such file named MyPipes exist already. fd = open ("MyPipes",O_WRONLY|O_CREAT); no O_CREAT, there is no file to be created.

  3. write (fd, ptr, strlen(ptr)); change it to write (fd, ptr, strlen(ptr)+1);

strlen will return the length withou "\0".

You failed to add the proper flag when open.

Try this:

fd = open ("mypipe11",O_WRONLY | O_CREAT);

EDIT:

Create the named pipe in writer before open using mkfifo.

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

char *ptr = "Akshit Soni";
int main()
{
        int fd;

        /* Create named pipe */
        mkfifo("MyPipes", 0666);

        /* open named pipe */
        fd = open ("MyPipes",O_WRONLY);

        write (fd, ptr, strlen(ptr));
        close (fd);
}

@paxdiablo already given command line method of creating named pipe.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top