[ create a new paste ] login | about

Link: http://codepad.org/iIUMh1FZ    [ raw code | output | fork ]

C++, pasted on Jun 6:
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <iostream>

using namespace std;

void echo(int fd[2]);
void grep(int fd[2]);

int main() {
	int fd[2];
	if (pipe(fd) == -1) {
		perror("pipe");
		exit(1);
	}

	echo(fd);
	grep(fd);

	sleep(2);
	return 0;
}


void echo (int fd[2]) {
	char *echo = "echo";
	char *argsE[] = { "echo", "12345\nabcd\n54321", NULL };
	pid_t fork1 = fork();
	if (fork1 == 0) {

		cout << "Echo PID: " << getpid() << endl;

		dup2(fd[1], 1);
		close(fd[1]);
		close(fd[0]);

		execvp(echo, argsE);
		cerr << "Error during echo" << endl;
		exit( -1 );
	}


	else {
		close(fd[0]);
		close(fd[1]);

		int status1 = 0;
		waitpid(fork1, &status1, 0);

		if (WIFEXITED(status1))
			cout << "Echo Exited: " << WEXITSTATUS(status1) << endl;
	}
}

void grep (int fd[2]) {
	char *grep = "grep";
	char *argsG[] = { "grep", "1", NULL };
	pid_t fork2 = fork();
	if (fork2 == 0) {
		cout << "Grep PID: " << getpid() << endl;

		dup2(fd[0], 0);
		close(fd[1]);
		close(fd[0]);

		execvp(grep, argsG);
		cerr << "Error during grep" << endl;
		exit( -1 );
	}

	else {

		close(fd[0]);
		close(fd[1]);

		int status2 = 0;
		cout << "Before wait" << endl;
		waitpid(fork2, &status2, 0);
		cout << "After wait" << endl;

		if (WIFEXITED(status2))
			cout << "Grep Exited: " << WEXITSTATUS(status2) << endl;
	}
}


Output:
1
2
3
4
5
6
7
8
9
cc1plus: warnings being treated as errors
In function 'void echo(int*)':
Line 27: warning: deprecated conversion from string constant to 'char*''
Line 28: warning: deprecated conversion from string constant to 'char*''
Line 28: warning: deprecated conversion from string constant to 'char*''
In function 'void grep(int*)':
Line 57: warning: deprecated conversion from string constant to 'char*''
Line 58: warning: deprecated conversion from string constant to 'char*''
Line 58: warning: deprecated conversion from string constant to 'char*''


Create a new paste based on this one


Comments: