'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);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
