2016-12-14 90 views
0

我使用stdin和stdout進行了通信,但我無法弄清楚在父進程中關閉它之後如何恢復stdin。在管道後恢復stdin

下面是一個例子:

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 
#include <sys/wait.h> 

void readPBM(char *output) 
{ 
    char tmp[1024]; 

    int fd[2] = {0,0}; 
    int pid; 

    //Open the pipe for inter-process communication 
    pipe(&fd[0]); 

    //Fork and test if we are child or parent process 
    pid = fork(); 
    if(pid) //Parent process 
    { 
     wait(NULL); //Wait for child's end 
     close(fd[1]);//Close pipe's write stream 
     close(0);//Close stdin 
     dup(fd[0]); 
     close(fd[0]); 

     strcpy(output, "");// Init output at 0 
     while(fgets(tmp, 1024, stdin) != NULL) //Put remainings entry in output 
     { 
      strcat(output, tmp); 
     } 
     strcat(output, "It works\n"); 
    } 
    else if(pid == 0) //Child process 
    { 
     close(fd[0]);//Close pipe's read stream 
     close(1);//Close stdout 
     dup(fd[1]);//Duplicate stdin 
     close(fd[1]); 

     printf("A random string ...\n"); 
     exit(0); 
    } 
    else //Print error if fork failed 
    { 
     printf("Error creating a new process"); 
     exit(EXIT_FAILURE); 
    } 
} 

int main(int argc, char *argv[]) 
{ 
    int i, j; 

    char *str = NULL; 
    char c; 

    str = malloc(512 * sizeof(char*)); 
    readPBM(str); 

    printf("%s", str); 

    c = getchar(); 
} 

我試圖挽救使用標準輸入:int stdin_copy = dup(0)然後恢復,但我的getchar不能正常工作。
我還試圖用freopen("/dev/stdin", "a", stdin)但它仍然不會等待輸入

回答

1

使用fdopen似乎運作良好所以這裏是固定的代碼:

#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 
#include <sys/wait.h> 

void readPBM(char *output) 
{ 
    FILE* fp; 
    char tmp[1024]; 

    int fd[2] = {0,0}; 
    int pid; 

    //Open the pipe for inter-process communication 
    pipe(&fd[0]); 

    //Fork and test if we are child or parent process 
    pid = fork(); 
    if(pid) //Parent process 
    { 
     wait(NULL); //Wait for child's end 
     close(fd[1]);//Close pipe's write stream 

     fp = fdopen(fd[0], "r"); 

     strcpy(output, "");// Init output at 0 
     while(fgets(tmp, 1024, fp) != NULL) //Put remainings entry in output 
     { 
      strcat(output, tmp); 
     } 
     strcat(output, "It works\n"); 
     fclose(fp); 
    } 
    else if(pid == 0) //Child process 
    { 
     close(fd[0]);//Close pipe's read stream 
     close(1);//Close stdout 
     dup(fd[1]);//Duplicate stdin 
     close(fd[1]); 

     printf("A random string ...\n"); 
     exit(0); 
    } 
    else //Print error if fork failed 
    { 
     printf("Error creating a new process"); 
     exit(EXIT_FAILURE); 
    } 
} 

int main(int argc, char *argv[]) 
{ 
    int i, j; 

    char *str = NULL; 
    char c; 

    str = malloc(512 * sizeof(char*)); 
    readPBM(str); 

    printf("%s", str); 

    c = getchar(); 
}