Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i receive a integer from a pipe

im trying to send a number from a process to his child, this using pipes, so i overwrite the standar output of the process to be send by the pipe output, then child is gonna receive it and use; but i receive an error that says the %d expects an int* and im giving an int, why?.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#define READ  0
#define WRITE 1

int main() {
    int randomNumber;
    srand(time(NULL));
    pid_t pid;
    int fd[2];

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

    switch(pid = fork()) {
        case 0:
        // The child process will execute wc.
        // Close the pipe write descriptor.
        close(fd[WRITE]);
        // Redirect STDIN to read from the pipe.
        dup2(fd[READ], STDIN_FILENO);
        //child receibe a number from the standar input
        fscanf(stdin, "%d", randomNumber);
        //once child receibed the random number, he print it
        if (randomNumber < 500) { 
            fprintf(stdout, "smaller than 500");
        }
        else {
            fprintf(stdout, "larger than 500");
        }

        case -1:
        perror("fork() failed)");
        exit(EXIT_FAILURE);

        default:
        //parent generates a random number between 1 and 1000
        randomNumber = rand()%(1000-1+1)+1;
        // The parent process will execute ls.
        // Close the pipe read descriptor.
        close(fd[READ]);
        // Redirect STDOUT to write to the pipe.
        dup2(fd[WRITE], STDOUT_FILENO);
        //i send to the child a random number
        fprintf(stdout, "%d", randomNumber);
    }
}   

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

try

fscanf(stdin, "%d", &randomNumber);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading