Public feed #528809

Something

public c v1 · immutable
Raw Edit
·published 2007-06-01 18:03 UTC
rendered paste body
#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/wait.h>#include <unistd.h>#include <errno.h>#include <string.h>#define MAXLENGTH 255const char *szCommand = "not set";static int pipe1[2];static pid_t pid1;static FILE* pStream1 = (FILE*) 0;void BailOut(const char* szMessage);void FreeResources() {	if(pStream1 != (FILE*) 0) {		if(fclose((FILE*) pStream1) == EOF) {			pStream1 = (FILE*) 0;			BailOut("Cannot close pipe");			}		}}void BailOut(const char* szMessage) {	if(szMessage != (const char*) 0) {		fprintf(stderr, "%s", szMessage);		}		FreeResources();	exit(EXIT_FAILURE);}void Usage() {	printf("Just start and write...");}void AllocateResources() {	if(pipe(pipe1) == -1) {		BailOut("Can't create pipe");		}}void FatherProcess() {	char c;	char buffer[MAXLENGTH +1];	char* p = buffer;		if(close(pipe1[0]) == -1) {		BailOut("Error closing the read descriptor");		}		if((pStream1 = fdopen(pipe1[1], "w")) == (FILE*) NULL) {		BailOut("Can't open pipe for writing");		}	/*	while((c = getchar()) != EOF) {		if(c != ' ') {			*p++ = c;			} else {			*p++ = '\0';			*p++ = '\n';			if(fprintf(pStream1, buffer) < 0) {				BailOut("Can't write to pipe");				}			p = buffer;			printf("%s\n", buffer);		}	}	*/		while(fgets(buffer, MAXLENGTH, stdin) != NULL) {		if(fprintf(pStream1, buffer) < 0)			BailOut("Can't write to pipe");	}		FreeResources();}void ChildProcess() {	char buffer[MAXLENGTH +1];	char reverse[MAXLENGTH +1];	char* p = buffer;			if(close(pipe1[1]) == -1) {		BailOut("Error closing the write descriptor");	}		if((pStream1 = fdopen(pipe1[0], "r")) == (FILE*) 0) {		BailOut("Can't open pipe for reading");	}		while(fgets(buffer, MAXLENGTH, pStream1) != NULL) {		p += strlen(buffer);		p -= 2;				int i;		for(i = 0; i < strlen(buffer); i++, p--) {			reverse[i] = *p;			}		printf("%s\n", reverse);	}		FreeResources();}int main(int argc, char** argv) {	pid_t wpid;	int status;		szCommand = argv[0];		AllocateResources();		switch(pid1 = fork()) {		case -1:			BailOut("Fork failed");				break;		case 0: 			ChildProcess();			break;		default:			FatherProcess();						while((wpid = wait(&status)) != pid1) {				if(wpid != -1) {					continue;					}									if(errno == EINTR) {					continue;				}								BailOut("Error waiting for child process");			}						break;				}		exit(EXIT_SUCCESS);}