Pipe in ein anderes Programm
von heinz- SNIPPET_TEXT:
-
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/wait.h>
- #include <string.h>
- const int PIPE_LESEN=0;
- const int PIPE_SCHREIBEN=1;
- int pipes[2];
- bool Pipe_verbinden(char*);// (externes_programm)
- int main()
- {
- /* Programmname */
- char bc_programm[]={"/usr/bin/bc"};
- Pipe_verbinden(bc_programm);// (externes_programm)
- /* Kurz warten bis bc gestartet */
- for(int z=0;z<100000;z++)
- {
- }
- /* Schreib und lese-speicher */
- char bufs[32]={""};
- char bufl[32]={""};
- /* Mehrere testformeln verschicken */
- for(int z=10;z<200;z+=10)
- {
- /* Formel erstellen */
- /* Formel senden */
- /* Lesespeicher leeren */
- /* Lesen */
- read(pipes[PIPE_LESEN],bufl,32);
- /* Ausgeben */
- }
- /* bc beenden */
- /* Pipes schliessen */
- close(pipes[PIPE_LESEN]);
- close(pipes[PIPE_SCHREIBEN]);
- }
- bool Pipe_verbinden(char* EP)// (externes_programm)
- {
- if(pipe(pipes)<0)
- {
- return(false);
- }
- pid_t kind_pid=fork();
- if(kind_pid<0)
- {
- close(pipes[PIPE_LESEN]);
- close(pipes[PIPE_SCHREIBEN]);
- return(false);
- }
- if(kind_pid==0)
- {
- close(0);
- dup2(pipes[0],0);
- close(pipes[0]);
- close(1);
- dup2(pipes[1],1);
- close(pipes[1]);
- execl(EP,EP,"-q",NULL);
- close(0);
- close(1);
- }
- return(true);
- }
- /*
- int main()
- {
- char bc_programm[]={"/usr/bin/bc"};
- pipe_end pipe;
- strlist list;
- int ok=pconnect(bc_programm,NULL,PIPE_WRITE,&pipe);
- }
- */
- /*
- //const int PIPE_READ = 0;
- //const int PIPE_WRITE = 1;
- int main()
- {
- int pipefds[2];
- if(pipe(pipefds)<0)
- {
- perror("pipe");
- exit(1);
- }
- pid_t child=fork();
- if(child<0)
- {
- perror("fork");
- exit(1);
- }
- if(child==0)
- {
- close(pipefds[PIPE_WRITE]);
- char buf[32];
- ssize_t nbytes;
- while((nbytes=read(pipefds[PIPE_READ],buf,sizeof(buf)))>0)
- {
- if(write(1,buf,nbytes)<nbytes)
- {
- exit(1);
- }
- }
- exit(0);
- }
- close(pipefds[PIPE_READ]);
- const char message[] = "Hello!\n";
- write(pipefds[PIPE_WRITE],message,sizeof(message)-1);
- close(pipefds[PIPE_WRITE]);
- wait(0);
- }
- */
Quellcode
Hier kannst du den Code kopieren und ihn in deinen bevorzugten Editor einfügen. PASTEBIN_DOWNLOAD_SNIPPET_EXPLAIN