Created
April 27, 2012 07:12
-
-
Save stetro/2506799 to your computer and use it in GitHub Desktop.
C Pipe zwischen 2 Programmen erstellen und beide Programme aufrufen
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
#include<unistd.h> | |
#define PARAM_ERROR "Falsche Angabe von Parametern !\n" | |
#define FORK_ERROR "Kinprozess konnte nicht erzeugt wernden !\n" | |
#define PIPE_ERROR "Pipe konnte nicht erzeugt werden !\n" | |
#define DUP2_ERROR "IO-Stream konnte nicht dupliziert werden !\n" | |
/* | |
Moeglicher Aufruf | |
./a.out <prog1> <prog2> | |
./a.out <prog1> <opt1> <prog2> | |
./a.out <prog1> <opt1> <prog2> <opt1> | |
./a.out <prog1> <prog2> <opt1> | |
*/ | |
int main(int argc, char * argv[]) | |
{ | |
// Parameter Array | |
char* arg1[3]; | |
arg1[0]=NULL;arg1[1]=NULL;arg1[2]=NULL; | |
char* arg2[3]; | |
arg2[0]=NULL;arg2[1]=NULL;arg2[2]=NULL; | |
// Laufvariable | |
int i; | |
int fork_pid; | |
int fd[2]; | |
// Parameter Abfrage | |
if(argc <= 2 || argc > 5) | |
{ | |
printf(PARAM_ERROR); | |
return EXIT_FAILURE; | |
} | |
// Parameter passend übernehmen | |
for(i = 1;i < argc; i++) | |
{ | |
switch(i) | |
{ | |
case 1: | |
arg1[0] = argv[i]; | |
break; | |
case 2: | |
if(argv[i][0] == '-') | |
{ | |
arg1[1] = argv[i]; | |
break; | |
} | |
case 3: | |
if(arg2[0] == NULL) | |
{ | |
arg2[0] = argv[i]; | |
break; | |
} | |
case 4: | |
arg2[1] = argv[i]; | |
break; | |
} | |
} | |
// Bei aufgetretenen Fehlern | |
if( arg2[0] == NULL ) | |
{ | |
printf(PARAM_ERROR); | |
return EXIT_FAILURE; | |
} | |
// Pipe erstellen | |
if(pipe(fd) < 0) | |
{ | |
printf(PIPE_ERROR); | |
return EXIT_FAILURE; | |
} | |
// 2 Prozesse starten | |
if((fork_pid = fork()) < 0) | |
{ | |
printf(FORK_ERROR); | |
return EXIT_FAILURE; | |
} | |
else if(fork_pid > 0) | |
{ | |
// PIPEN DES PROZESSES 1 | |
// stdin schließen und fd[0] duplizieren | |
if(dup2(fd[0], 0) < 0) | |
{ | |
printf("DUP2_ERROR"); | |
return EXIT_FAILURE; | |
} | |
close(fd[1]); // schreibe seite der pipe schliessen | |
execvp(arg2[0],arg2); // Programm starten | |
} | |
else | |
{ | |
// PIPEN DES PROZESSES 2 | |
// stdout schließen und fd[1] duplizieren | |
if(dup2(fd[1], 1)<0) | |
{ | |
printf("DUP2_ERROR"); | |
return EXIT_FAILURE; | |
} | |
close(fd[0]); // lese seite der pipe schliessen | |
execvp(arg1[0],arg1); // Programm starten | |
} | |
// Programm beenden | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment