Home > Net >  Sending a single letter using pipes in C
Sending a single letter using pipes in C

Time:10-31

I am trying to send a string using a pipe from parent to child one character at a time. In order to do that, I am passing that character to the write statement using a for loop as follows :

for(int j=0; j<strlen(str); j  ){
    write(fd[WRITE_END], str[j], BUFFER_SIZE);
}

However, the code does not compile successfully and shows the following:

warning: passing argument 2 of ‘write’ makes pointer from integer without a cast [-Wint-conversion]
write(fd[WRITE_END], str[j], BUFFER_SIZE);

and

note: expected ‘const void *’ but argument is of type ‘charextern ssize_t write (int __fd, const void *__buf, size_t __n) __wur;

What did I do wrong? Is it not possible to send single characters using pipes?

Any help is appreciated.

CodePudding user response:

Please refer to the documentation for "write()":

https://man7.org/linux/man-pages/man3/write.3p.html

#include <unistd.h>

ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
           off_t offset);
ssize_t write(int fildes, const void *buf, size_t nbyte);

In other words, if you want to write one character, you need to:

  • Specify the address of that character, and

  • Specify "one byte":

    for(int j=0; j<strlen(str); j  ){
      write(fd[WRITE_END], &str[j], 1);
    }
    
  •  Tags:  
  • c
  • Related