LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   read and pipe function (https://www.linuxquestions.org/questions/programming-9/read-and-pipe-function-96286/)

dummyagain 09-24-2003 09:23 AM

read and pipe function
 
How to use the read(fd, ?/, ??) to read the line in the other file?

and also what's the use of pipe() and can u suggest some examples for showing the usage?

Thanks

SaTaN 09-24-2003 10:26 AM

READ ::-

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.
Code:

#include<stdio.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
main()
{
        int fd=open("file",O_RDONLY);
        char BUFF[50];
        while(read(fd,BUFF,50)!=0)
                printf("%s",BUFF);
}


SaTaN 09-24-2003 10:30 AM

PIPES :-
Pipes are mainly used for Inter Process Communication ....
Code:

#include <stdio.h>
#include <unistd.h>
main()
{
        int  pipefd[2];
        int pid;
        char child_buff[100] = "This is a buffer :: I am doing IPC";
        char parent_buff[100];
        if( pipe(pipefd) < 0)
        {
                printf("Error in creating pipe!\n");
                return;
        }
        if( (pid = fork()) < 0)
        {
                printf("Error in fork\n");
                return;
        }
        if(pid == 0)
        {
                if( write(pipefd[1], child_buff, 50) < 0)
                {
                        printf("write error!\n");
                        return;
                }
        }
        else
        {
                read(pipefd[0], parent_buff, 50);
                printf("%s\n", parent_buff);
        }
}

You can do "man 2 pipe" and "man 2 read" to get more information about these two functions...

dummyagain 09-24-2003 10:48 AM

What's the buf in read() ? How do we determine its value?

dummyagain 09-24-2003 10:50 AM

My concept to the pipe() is still not clear, can anybody show me an example, say to access a folder and check the no of file, can the pipe() do this?

Hko 09-24-2003 11:08 AM

Quote:

Originally posted by dummyagain
What's the buf in read() ? How do we determine its value?
It's a string, or, in C an array of char's.
After it's declared ( char buf[50]; ) there memory set aside to contain 50 char's. After this declaration the bytes (char's) are there for you to use, but only contain garbage, i.e. it contains undefined bytes. But they get overwritten by the read() function with the contents from the file read() is reading. So, after read(), the bytes now have a meaning (text from the file).

buf points to the first char (byte) of the array, which is buf[0]. When reading text, and you want to handle buf like a string (e.g. print it with puts() / printf(), or compare it with another string with strncmp() ), then you can only store 49 char's because the last needs to be the special null-character ( '\0' ) for the string handling to know where it ends.

Here's a larger example. Maybe it helps:
Code:

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

/* Reads the first line of a file and prints it.
 * The name of the file must be given as the
 * only argument on the command line.
 * The maximum length of the line read and printed
 * is defined below (MAXLEN).
 */

#define MAXLEN 100

int main(int argc, char *argv[])
{
    int fd;
    int count, i;
    char line[MAXLEN + 1];

    if (argc != 2) {
          fprintf(stderr, "\nUsage: %s <filename>\n\n", argv[0]);
          return 1;
    }

    fd = open(argv[1], O_RDONLY);
    if (fd < 0) {
          perror("Error opening file");
          return 1;
    }

    count = read(fd, line, MAXLEN);
    if (count < 0) {
          perror("Error reading file");
          return 1;
    }

    /* Find the end of the line and make it the end of the
      * string.  (it's possible we read more than 1 line)
      * Another option would be to read() one byte at a time
      * using read(fd, line, 1), and then check for this
      * after each byte read.
      */
    for (i = 0; i < count ; ++i) {
          if (line[i] == '\n') {
              line[i] = '\0';
              break;
          }
    }

    /* If no '\n' found, then the line was longer than MAXLEN
      * And the line will be truncated. In that case we have to
      * make sure the string is terminated at the end.
      */
    line[MAXLEN] = '\0';

    /* Print the line */
    printf("%s\n", line);
    return 0;
}


Hko 09-24-2003 11:21 AM

Quote:

Originally posted by dummyagain
My concept to the pipe() is still not clear, can anybody show me an example, say to access a folder and check the no of file, can the pipe() do this?
No, pipe() cannot do that. Use stat() and/or readdir() for that.
But don't bother until you understand C better, and understand things like "char buf[50]" and struct's well.

A pipe is use to connect two processes (say "programs"), where one process read output from the other. pipe() is used mostly when your program starts another program, or creates another process running the same program, and you want to pass data from your program to the other.

These kind of functions (popen(), pipe(), ...) are used by the shell (bash) for example to make things possible like this:

$ zcat somefile.txt.gz | sort | uniq | fgrep someword

(this example doesn't really make sense, just to illustrate pipes)

I don't mean to offend...but if you don't what pipes are and what they do, and don't understand C reasonably well, I would not bother trying to write programs using pipe() and read(). These aren't the most easy functions to start with.

Hope I could help a bit anyway.

dummyagain 09-24-2003 11:26 AM

Yes, I am just a beginner in using C (I used to use C++, but I need to learn it due to the project)...

I just wonder if I can use the pipe() to do that

One of the side of the pipe is for standard input while other side is for standard output. If I put the folder in the input and make it count the no of file in the folder and then output it to the output of other side (The standard output). The two sides of the pipe will be used by using folk() to produce both parent and child....

can it work?

SaTaN 09-24-2003 11:47 AM

Yes it sure will work .... All that you have to do is pass the no. of files as the input through child_buff in the program I have already
posted....

There the string "This is a buffer :: I am doing IPC" was being transmitted....

P.S :- I suppose you know the functions required to count no. of files i.e, scandir()....

rmurberger 09-24-2003 03:21 PM

Pipe
 
How do you type the pipe symbol? I know I read it somewhere but now that I need it I cant find it. A REAL Newbie question!!

Hko 09-24-2003 03:46 PM

Re: Pipe
 
Quote:

Originally posted by rmurberger
How do you type the pipe symbol?
By pushing gently on the button on your keyboard that says: |
There are about more than 100 (!) buttons on your keyboard, so you may have to have a look at all of them to find it. Sorry, there's no easier way, no hacker tricks or shortcuts available here.

If it is on a button together with another symbol and the | is the top one, it gets a little complex:

Before you gently press the button, you have to press and hold another button on the keyboard that says: "Shift". Fortunately there are two of them and it does not matter which one you use, and they usually are slightly larger than the most buttons, so you should be able to find them relatively easily. After you have pressed the button saying | while holding one of the shift buttons, you can also release the shift button.

Good luck!

Quote:

A REAL Newbie question!!
More or less...

rmurberger 09-24-2003 03:57 PM

Pipe
 
Thanks for for your sarcastic response Hko. I have 3 keyboards and none have a pipe key. I may new to Linux but I'm hardly new to keyboards and not stupid either. If I had a pipe symbol on my keyboard I wouldnt be asking such a "stupid" question. These things and sarcastic responses from people like you certainly dont encourage windows users like me to make the transition to Linux.

Hko 09-24-2003 05:47 PM

OK, you're right. I should not have done that.
I could not resist the temptation, I guess.
It didn't come to my mind there would be PC-keyboards without the |.
This was stupid of me, because obviously there could be keyboards for languages-other-than-english (or dutch for that matter) that do not have hey for |. What kind of keyboard are you using?

Actually, I do not know a simple answer to your question.

I apologize

Quote:

These things and sarcastic responses from people like you certainly dont encourage windows users like me to make the transition to Linux.
True.

shellcode 09-24-2003 10:36 PM

if you want to learn about pipes and other types of UNIX IPC check out:
http://www.ecst.csuchico.edu/~beej/guide/ipc/

SysV things too


All times are GMT -5. The time now is 02:15 AM.