Day 9
Day 9
When you create a pipe, the kernel gives you two file descriptors:
Descriptor pipedes[0] is for reading and pipedes[1] is for writing. Whatever is written
into pipedes[1] can be read from pipedes[0].
To check if a pipe has been successfully created, you can verify the return value
of the pipe() system call. The pipe()function returns 0 if the pipe creation is
successful and -1 if there is an error.
Example:
int num;
read(fd[0], &num, sizeof(num));
int main() {
int pipefd[2]; // Declare the pipe array: pipefd[0] = read end, pipefd[1] = write end
pid_t pid; // Declare a variable for process ID
int number = 42; // Number that the parent will send to the child
close(pipefd[1]); // Close unused write end of the pipe in the child process
int received_number; // Variable to store the received number from the pipe
read(pipefd[0], &received_number, sizeof(received_number)); // Read the
number from pipe
Practice: