Howdy,...
I trying to create a pipe between two applications (gui and console) for that i need to understand the pipeing world ...
A console application uses stdin and stdout and i wish to pipe it to the gui application so stdin of console application will be stdout of gui and stdout of console will be stdin of gui application.
i read the man file of dup2() , popen() , pipe() and abit stuck.
i wish to achieve the next :
parent send command to child.
child do some thing and answer to parent
parent print the answer.
Using a tutorial :
Code:#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main(){ pid_t pid; int rv; int commpipe[2]; /* This holds the fd for the input & output of the pipe */ char str[] = "Whats up dock?"; /* Setup communication pipeline first */ if(pipe(commpipe)){ fprintf(stderr,"Pipe error!\n"); exit(1); } /* Attempt to fork and check for errors */ if( (pid=fork()) == -1){ fprintf(stderr,"Fork error. Exiting.\n"); /* something went wrong */ exit(1); } if(pid){ /* A positive (non-negative) PID indicates the parent process */ dup2(commpipe[1],1); /* Replace stdout with out side of the pipe */ close(commpipe[0]); /* Close unused side of pipe (in side) */ setvbuf(stdout,(char*)NULL,_IONBF,0); /* Set non-buffered output on stdout */ scanf("%s",str); printf("%s\n",str); fprintf(stderr,"Gui sent %s \n",str); //Just to be sure. wait(&rv); /* Wait for child process to end */ fprintf(stderr,"Child exited with a %d value\n",rv); } else{ /* A zero PID indicates that this is the child process */ dup2(commpipe[0],0); /* Replace stdin with the in side of the pipe */ close(commpipe[1]); /* Close unused side of pipe (out side) */ /* Replace the child fork with a new process */ if(execl("child","child",NULL) == -1){ fprintf(stderr,"execl Error!"); exit(1); } } return 0; }
Code:/** * The idea is to alter stdin and stdout : * * this part should use parent procces (parent.c) as its keyboard and screen * i wish to run this application as a demon. */ #include <stdio.h> int main(){ char string[100]; printf("External Process\n"); do{ printf("Enter Command: "); fflush(stdout); /* Must flush to see command prompt */ fgets(string,100,stdin); printf("(child got) %s\n",string); /* No flush necessary because new line flushes */ }while(!strstr(string,"exit")); return 0; }



LinkBack URL
About LinkBacks


