LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 09-14-2005, 10:19 AM   #1
neo_in_matrix
Member
 
Registered: Sep 2003
Posts: 52

Rep: Reputation: 15
Newbie on forking child process and I/O redirection


Hi, I am new to child process concept under Linux. I want a simple but complete example code that demonstrates the following basics of forking child process:

1. Forking a child process.
2. Redirecting its stdin and stdout.
3. The parent process writes to stdout and at the same time reads child stdout.

Thanks for any information.
 
Old 09-14-2005, 10:47 AM   #2
kees-jan
Member
 
Registered: Sep 2004
Distribution: Debian, Ubuntu, BeatrIX, OpenWRT
Posts: 273

Rep: Reputation: 30
"simple but complete example code"...

People get more and more demanding these days....

Off the top of my head, the best I can do is some pseudocode. It'll be simple, but you have to complete it :-)

Code:
// Pseudocode. This will not compile and/or contain severe syntax errors

// Omitted error checking for simplicity. Don't try this at home

int main ()
{
    int fd[2]; // file descriptors

    // Create pipe
    pipe(fd);

    // Fork child process
    if (fork() == 0)
    {
        char buffer [80];
        
        // We're in the child process

        // close stdin
        close(0);

        // connect pipe to stdin
        dup(fd[0]);
        close(fd[0]);

        // read from stdin
        gets(buffer);

        // Prove that it worked
        printf("Parent said %s", buffer);
    }
    else
    {
        // We're in the parent process

        // close stdout
        close(1);

        // connect pipe to stdout
        dup(fd[1]);
        close(fd[1]);

        // Write to standard out
        printf ("Hello world!\n");
    }
    // the end
    return 0;
}
For details, refer to the manpages of the used functions. Or ask more specific questions

Groetjes,

Kees-Jan
 
Old 09-15-2005, 02:03 AM   #3
neo_in_matrix
Member
 
Registered: Sep 2003
Posts: 52

Original Poster
Rep: Reputation: 15
Thanks for replying.

I tested the code, it worked. But it's not exactly what I want.

What I want is bascially the same as what Eclipse does with gdb. It spawns gdb as its child process and writes commands to the child process and retrieves gdb's output and displays or parses the captured output.

Have I made my problem clear?
 
Old 09-15-2005, 04:49 AM   #4
neo_in_matrix
Member
 
Registered: Sep 2003
Posts: 52

Original Poster
Rep: Reputation: 15
Oops, I have found a solution myself after 3 hours of struggling. The program runs fine, but I wonder if I am making minor mistakes. See my code below:

Code:
void test_pipe()
{
	int		pipe1[2];
	int		pipe2[2];
	pid_t	pid;

	pipe(pipe1);
	pipe(pipe2);

	pid = fork();
	if(pid == 0)
	{
		puts("In child process");
		close(pipe1[1]);
		dup2(pipe1[0], STDIN_FILENO);

		close(pipe2[0]);
		dup2(pipe2[1], STDOUT_FILENO);

		puts("Spawning 'sort'");
		execlp("sort", "sort", 0);
	}
	else
	{
		puts("In parent process");
		close(pipe1[0]);

		puts("Writing to child input");
		FILE* fpw = fdopen(pipe1[1], "w");
		srand(time(0));
		puts("How many random numbers?");
		char* str = safegets();
		int n = atoi(str);
		for(int i = 0; i < n; i++)
		{
			fprintf(fpw, "%d\n", rand());
		}
		fclose(fpw);
		close(pipe1[1]);

		puts("Reading child output");
		close(pipe2[1]);
		char buf[1000];
		FILE* fpr = fdopen(pipe2[0], "r");
		n = 0;
		while(fgets(buf, 1000, fpr))
		{
			printf("#%d:%s", n, buf);
			n++;
		}
		fclose(fpr);
		close(pipe2[0]);
		puts("End of child output");

		puts("Waiting for child close");
		waitpid(pid, 0, 0);
	}
}

Last edited by neo_in_matrix; 09-15-2005 at 04:51 AM.
 
Old 09-16-2005, 03:05 AM   #5
kees-jan
Member
 
Registered: Sep 2004
Distribution: Debian, Ubuntu, BeatrIX, OpenWRT
Posts: 273

Rep: Reputation: 30
Wow... This is most impressive...

Two minor points:

After executing, for example
Code:
		close(pipe1[1]);
		dup2(pipe1[0], STDIN_FILENO);
you still have filedescriptor pipe1[0] open, but you no longer need it, so you might as well close it, like so:
Code:
		close(pipe1[1]);
		dup2(pipe1[0], STDIN_FILENO);
		close(pipe1[0]);
Secondly, in the parent, you first write a lot of stuff to the client process, and then proceed to read its output. In this case, this is fine, because 'sort' doesn't output anything before reading the last line of input.

Other programs (grep or cat being examples) may want to start writing output before reading the complete input. If these can't write output, they may stop reading input, causing your parent program to block on the writes. That would cause a deadlock.

Pipes do include some buffering, so this will only happen for "large" inputs and outputs, but it is still something worth considering.

Groetjes,

Kees-Jan

Last edited by kees-jan; 09-16-2005 at 03:09 AM.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
how a father process know which child process send the signal SIGCHLD icoming Programming 10 07-20-2010 07:26 AM
How to kill a Child and all its subsequent child process in C shayer009 Programming 3 12-04-2007 12:40 AM
forking 7 child processes ianomc Programming 5 11-07-2004 12:33 PM
Killing a child process from another child marri Programming 6 10-01-2004 07:08 PM
Question on forking a child process brianvdc Programming 2 10-16-2003 04:07 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 08:35 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration