Hello Members,

I have the following question about the pipe() system call. Say, Process A (my main()) forks a Process B which then forks a Process C. How can I open a pipe between Process C and Process A? I would like to write a sentence in Process C and read it in Process A. Right now, I am only able to read/write from Process A to Process B and read/write from Process B to Process C. Any pseudocode/example code will be of great help.

Thank you!
sciprog1

Its been some time since I looked at pipes so I would go over this code with a fine tooth comb...You'll probably find places in the code that need improvement.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

enum PIPES {READ, WRITE};

int main(int argc, char**argv)
{
	char ch[] = "This is the message to pass along to the end\n";
	int hpipe[2];

	pipe(hpipe);

	if (fork())
	{
		close(hpipe[READ]);
		write(hpipe[WRITE], ch, strlen(ch));
		close(hpipe[WRITE]);		
	}
	else
	{

		if (fork())
		{
			/*does nothing*/	
		}
		else
		{
			char final[2];
			int n = 0;
			close(hpipe[WRITE]);
			while ((n = read(hpipe[READ], final, 1)) > 0)
			{
				final[n] = '\0';
				fputs("->", stdout);
				fputs(final, stdout);
				fputs("\n", stdout);				
			}
			close(hpipe[READ]);
		}
	}
	exit(EXIT_SUCCESS);
}

Hello gera,

Thanks a lot! That was helpful

Regards

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.