Search code examples
cpipe

write on pipe in C


I am trying to create a program that is basically has 2 processes. the first takes a string from the user and passes it to the other. the 2nd read the string from the pipe. capitalize it then send it back to the first process. the 1st then print the 2 stings.

My code does pass the String and the other process reads it and capitalize it but I think there is an error in either writing the 2nd time or reading the 2nd time. here is the code:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#define SIZE 15

int main() {
    int fd[2];
    pipe(fd);
    if(fork() == 0) {
        char message[SIZE];
        int length;
    
        close(fd[1]);
        length = read(fd[0], message, SIZE);
        for(int i=0;i<length;i++) {
            message[i]=toupper(message[i]);
        }
        printf("%s\n",message);
        close(fd[0]);
    
        open(fd[1]);
        write(fd[1], message, strlen(message) + 1);
        close(fd[1]);
    } else {
        char phrase[SIZE];
        char message[SIZE];
        printf("please type a sentence : ");
        scanf("%s", phrase);
        close(fd[0]);
        write(fd[1], phrase, strlen(phrase) + 1);
        close(fd[1]);
    
        sleep(2);
    
        open(fd[0]);
        read(fd[0], message, SIZE);
        close(fd[0]);
        printf("the original message: %s\nthe capitalized version: %s\n",phrase,message);
    }
    return 0;
}

Solution

  • Here's a demo of a two-pipe solution... keeping the "scanf()" you imployed which only captures the first word... not all input:

    #include <stdio.h>
    #include <unistd.h>
    #include <ctype.h>
    #include <string.h>
    #include <signal.h>
    
    #define SIZE 15
    
    int main()
    {
        int to_child_fd[2];
        int to_parent_fd[2];
        pipe(to_child_fd);
        pipe(to_parent_fd);
    
        if (fork() == 0) {
        char message[SIZE];
        int length;
    
        close(to_child_fd[1]);  /* child closes write side of child  pipe */
        close(to_parent_fd[0]); /* child closes read  side of parent pipe */
        length = read(to_child_fd[0], message, SIZE);
        for (int i = 0; i < length; i++) {
            message[i] = toupper(message[i]);
        }
        printf("child: %s\n", message);
        write(to_parent_fd[1], message, strlen(message) + 1);
        close(to_parent_fd[1]);
        } else {
    
        char phrase[SIZE];
        char message[SIZE];
        printf("please type a sentence : ");
        scanf("%s", phrase);
        close(to_parent_fd[1]); /* parent closes write side of parent pipe */
        close(to_child_fd[0]);  /* parent closes read  side of child  pipe */
        write(to_child_fd[1], phrase, strlen(phrase) + 1);
        close(to_child_fd[1]);
    
        read(to_parent_fd[0], message, SIZE);
        printf("the original message: %s\nthe capitalized version: %s\n", phrase, message);
        }
        return 0;
    }