我如何从管道接收整数
how can i receive a integer from a pipe
我试图从一个进程向他的 child 发送一个数字,这使用管道,所以我覆盖了管道输出发送的进程的标准输出,然后 child 是会收到并使用;但我收到一条错误消息 the %d expects an int* and im giving an int
,为什么?
#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);
}
}
尝试
fscanf(stdin, "%d", &randomNumber);
我试图从一个进程向他的 child 发送一个数字,这使用管道,所以我覆盖了管道输出发送的进程的标准输出,然后 child 是会收到并使用;但我收到一条错误消息 the %d expects an int* and im giving an int
,为什么?
#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);
}
}
尝试
fscanf(stdin, "%d", &randomNumber);