簡體   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