Work as pipe in UNIX?

The man page for the channels are given here's an example of the use of the channels:
main(int argc, char *argv[])
{
 int pipefd[2];
 pid_t cpid;
 char buf;

 if (argc != 2) {
 fprintf(stderr, "Usage: %s <string>\n", argv[0]);
exit(EXIT_FAILURE);
}

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

 cpid = fork();
 if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}

 if (cpid == 0) { /* Child reads from pipe */
 close(pipefd[1]); /* Close unused write end */

 while (read(pipefd[0], &buf, 1) > 0)
 write(STDOUT_FILENO, &buf, 1);

 write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);

 } else { /* Parent writes argv[1] to pipe */
 close(pipefd[0]); /* Close unused read end */
 write(pipefd[1], argv[1], strlen(argv[1]));
 close(pipefd[1]); /* Reader will see EOF */
 wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
 }</string>

Can't understand why you can be sure that the first parent will write something to the channel, and only then the descendant will try something to consider. Could occur a situation in which the offspring tries to read data from a channel until there's something will appear?

And in General how to make so that process would Wake up only when there's something to read? To read everything that is and was filled back in? How it works at the OS level?
August 19th 19 at 23:13
1 answer
August 19th 19 at 23:15
Solution
You use blocking read/write, so the read operation will wait until data. On the lock time, the process will fall asleep, in addition to this nothing else to do. If the recording process is to write a fairly large amount of data and the reading process will not have time to read the data then will be filled the buffer pipe'and then will be blocked by the write operation and "sleep" will writing process.
Now, if you want to avoid locks, it is necessary to translate the descriptors in blokiruy mode and use select()/poll() or analogues.

OS-level pipe() is just a buffer memory in which data can be read and written through the descriptor.
And how do these lock? How the OS decides at what point a process should Wake up? - joshuah_Williamson commented on August 19th 19 at 23:18
if the process waits for the read lock will fail with the appearance of data in the buffer. If the process is waiting to be recorded, then the lock will be completed with the appearance of free space in the buffer. The OS decides this at the time of processing of the relevant event. For example, one process writes into the pipe, the operating system in the processing of entries sees that there is a process the pending data and "awakens" the corresponding flow. - christina_Bruen4 commented on August 19th 19 at 23:21

Find more questions by tags C* nix-like systemsConveyor