Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This program creates a new process and provides a simple pipe to
- * allow the child to communicate with the parent
- * Version 1 -- explicitly using pipe and byte-oriented read/write
- * type 'quit' to exit program
- */
- #include <sys/types.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- // Maximum number of letters to be communicated
- #define MAX 40
- int main() {
- // File descriptor array for the pipe
- // * fd[0] will be the end you can read from
- // * fd[1] will be the end you can write to
- int fd[2];
- // Character array (string) for reading
- char line[MAX];
- char input[MAX];
- pid_t pid;
- // Create a pipe and check for errors
- if(pipe(fd) == -1) {
- perror("pipe error");
- exit(EXIT_FAILURE);
- }
- // Fork a child process and check for errors
- pid = fork();
- if(pid == -1) {
- perror("error in fork");
- exit(EXIT_FAILURE);
- }
- if(pid == 0) {
- // Processing for the child process only
- printf("The child process is active.\n");
- // Close the writable end of the pipe, leaving the readable end open
- close(fd[0]);
- // Write a string to the pipe and indicate its length (in bytes)
- do {
- scanf("%s", input);
- write(fd[1], input, 26);
- } while (strcmp(line, "quit") != 0);
- } else {
- // Processing for the parent process only
- printf("The parent process is active.\n");
- // Close the readable end of the pipe, leaving the writable end open
- close(fd[1]);
- // Read from the pipe
- do
- {
- read(fd[0], line, MAX);
- printf("recieved %s\n", line);
- } while (strcmp(line, "quit") != 0);
- }
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement