繁体   English   中英

我如何从 pipe 接收 integer

[英]how can i receive a integer from a pipe

我试图从一个进程向他的孩子发送一个数字,这个使用管道,所以我覆盖了由 pipe Z78E6221F6393D1356681DB398F14CED6 发送的进程的标准 output Z78E6221F6393D1356681DB398F14CED6 但我收到一个错误,说 %d 需要一个 int* 并且我给出一个 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM