Sponsored Content
Full Discussion: Pipe between Childs
Top Forums Programming Pipe between Childs Post 302728191 by Poppo on Wednesday 7th of November 2012 12:45:50 PM
Old 11-07-2012
Pipe between Childs

Hey guys,

I have to make a C program that simulates this command :

cat (files here) | sort > file.txt

So, I start and create a pipe. Then create the first child. This first child will execute the Cat through the pipe. Then create a second child that will execute sort, with input from pipe. And redirect output to the file.

So, I have this fragment of code, but the program doesn't execute the Sort and it shows me the error message instead.

Code:
..... variables here ....

if (pipe(tub) < 0) panic("Creació pipe");  /* pipe creation */
 
   switch (fork()) /* First child will exec Cat */ 
   { 
    
    case -1: panic("Fork 1"); 
     
    case 0: 
     
    close(1); dup(tub[1]); 
    close(tub[0]); close(tub[1]); 
     
    arg_list[0] = "cat";       /* Input files for Cat */
    for (p=0; p<Nfitxers; p++) { 
    pid = Pids[p]; 
    sprintf(s, "%d_Winners.txt", pid); 
    arg_list[p+1]= strdup(s); 
    } 
     
    arg_list[Nfitxers]= NULL; 
     
    execv("/bin/cat", arg_list);  /* Execute Cat here */
    panic("Executant execv cat"); 
 
    
    default: 
    break; 
   } 
    
   switch (fork()) /* Second child execut Sort */ 
   { 
    
    case -1: panic("Fork 2"); 
     
    case 0: 
     
    close(0); dup(tub[0]); 
    close(tub[0]);  
 
/* Creating Output file here */

    if ((dest = open("Winners.txt", O_WRONLY|O_TRUNC|O_CREAT, 0600))<0) { 
       panic("Creació del fitxer destí"); } 
 
     
    dup2(dest,STDOUT_FILENO);    /* Redirect output to file */
    dup2(dest,STDERR_FILENO);  
    close(dest);  
     
    execl( "sort" , "sort", NULL );   /* Executing sort */
    panic("Executant execl sort"); 
 
     
    default: 
    break; 
    
   } 
    
   close(tub[0]);  
   close(tub[1]); 
    
    
   wait(&st1); 
   wait(&st2);

 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Is there any cmd to kill a process including its childs ( or sub processes spawned by

Dear Unix Gurus, Here is my query. If i start a script,it inturn calls many other scripts ..and most of them continue to run in parallel. Suppose,if i want to stop my script for some reason,i need to kill -9 each of the processes running.It becomes clumsy if the sub processes r more. ... (15 Replies)
Discussion started by: gvsreddy_539
15 Replies

2. Shell Programming and Scripting

How to kill a process and its childs given pid and userid

I need to write a shell script which would take 2 arguments pid , userid. Then it should kill all the child process under it. If a child process is not killed then it should wait for 1 minute and should kill. can anybody give me the idea to write it? (0 Replies)
Discussion started by: nani_g
0 Replies

3. Programming

share file descriptor between childs

#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <fcntl.h> #include <signal.h> #include <unistd.h> #include <string.h> #define BUFF_SIZE 256 #define CHILDS 4 #define DATAFILE "Client_Files.txt" void worker(int n);... (3 Replies)
Discussion started by: dlcpereira
3 Replies

4. Programming

forking. sharing global data in childs

hi, i want to write a code for forking 3 4 child. n wants that every child process one of the account from global account list. i wrote a program for that, but problem is every child is processing every account in list. what can me done to avoid it. attaching code with it #include <stdio.h>... (2 Replies)
Discussion started by: anup13
2 Replies

5. Programming

Need help with fork, forking multiple childs and shared memory

Hi all, I m writing an application, where i need to fork multiple childs and those child should handle particular task given to them. More descriptive. For example, suppose i have 4 Network, each network has multiple nodes. Now on the basis of network child should be forked and these child... (8 Replies)
Discussion started by: helpmeforlinux
8 Replies

6. Programming

waiting for multiple childs - C - waitpid

Hi gurus, I would like to fork more children and then write their return values: so far I tried: #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main(void) { pid_t pid; int rv=0, i; ... (5 Replies)
Discussion started by: wakatana
5 Replies

7. Shell Programming and Scripting

How can I use pipe

Hi, guys: I am working on my shell using c. How can I use pipe to implement the following? ls -l 1>> | grep hellp 1<< 2>> | less 2<< (the output of ls goes to grep, and the output of grep goes to less) Thanks Please use and tags when posting code, data or logs etc. to preserve... (1 Reply)
Discussion started by: tomlee
1 Replies

8. Shell Programming and Scripting

Replace pipe with Broken Pipe

Hi All , Is there any way to replace the pipe ( | ) with the broken pipe (0xA6) in unix (1 Reply)
Discussion started by: saj
1 Replies

9. Programming

How Can I share a socket between childs?

Hello guys! I had seen some posts at this forum talking about my problem, but maybe my scenario is a little different, and I want other solutions. I saw users of this forums saying that the way to shared sockets is using UNIX Sockets, but this is the only way in my scenario? My Scenario:... (4 Replies)
Discussion started by: serpens11
4 Replies

10. Shell Programming and Scripting

How to ignore Pipe in Pipe delimited file?

Hi guys, I need to know how i can ignore Pipe '|' if Pipe is coming as a column in Pipe delimited file for eg: file 1: xx|yy|"xyz|zzz"|zzz|12... using below awk command awk 'BEGIN {FS=OFS="|" } print $3 i would get xyz But i want as : xyz|zzz to consider as whole column... (13 Replies)
Discussion started by: rohit_shinez
13 Replies
Proc::Fork(3pm) 					User Contributed Perl Documentation					   Proc::Fork(3pm)

NAME
Proc::Fork - Simple, intuitive interface to the fork() system call VERSION
This documentation describes Proc::Fork version 0.71 SYNOPSIS
use Proc::Fork; run_fork { child { # child code goes here. } parent { my $child_pid = shift; # parent code goes here. waitpid $child_pid, 0; } retry { my $attempts = shift; # what to do if if fork() fails: # return true to try again, false to abort return if $attempts > 5; sleep 1, return 1; } error { # Error-handling code goes here # (fork() failed and the retry block returned false) } }; DESCRIPTION
This module provides an intuitive, Perl-ish way to write forking programs by letting you use blocks to illustrate which code section executes in which fork. The code for the parent, child, retry handler and error handler are grouped together in a "fork block". The clauses may appear in any order, but they must be consecutive (without any other statements in between). All four clauses need not be specified. If the retry clause is omitted, only one fork will be attempted. If the error clause is omitted the program will die with a simple message if it can't retry. If the parent or child clause is omitted, the respective (parent or child) process will start execution after the final clause. So if one or the other only has to do some simple action, you need only specify that one. For example: # spawn off a child process to do some simple processing run_fork { child { exec '/bin/ls', '-l'; die "Couldn't exec ls: $! "; } }; # Parent will continue execution from here # ... If the code in any of the clauses does not die or exit, it will continue execution after the fork block. INTERFACE
run_fork run_fork { ... } Performs the fork operation configured in its block. child child { ... } Declares the block that should run in the child process. parent parent { ... } Declares the block that should run in the parent process. The child's PID is passed as an argument to the block. retry retry { ... } Declares the block that should run in case of an error, ie. if "fork" returned "undef". If the code returns true, another "fork" is attempted. The number of fork attempts so far is passed as an argument to the block. This can be used to implement a wait-and-retry logic that may be essential for some applications like daemons. If a "retry" clause is not used, no retries will be attempted and a fork failure will immediately lead to the "error" clause being called. error error { ... } Declares the block that should run if there was an error, ie when "fork" returns "undef" and the "retry" clause returns false. The number of forks attempted is passed as an argument to the block. If an "error" clause is not used, errors will raise an exception using "die". EXAMPLES
Simple example with IPC via pipe use strict; use Proc::Fork; use IO::Pipe; my $p = IO::Pipe->new; run_fork { parent { my $child = shift; $p->reader; print while <$p>; waitpid $child,0; } child { $p->writer; print $p "Line 1 "; print $p "Line 2 "; exit; } retry { if( $_[0] < 5 ) { sleep 1; return 1; } return 0; } error { die "That's all folks "; } }; Multi-child example use strict; use Proc::Fork; use IO::Pipe; my $num_children = 5; # How many children we'll create my @children; # Store connections to them $SIG{CHLD} = 'IGNORE'; # Don't worry about reaping zombies # Spawn off some children for my $num ( 1 .. $num_children ) { # Create a pipe for parent-child communication my $pipe = IO::Pipe->new; # Child simply echoes data it receives, until EOF run_fork { child { $pipe->reader; my $data; while ( $data = <$pipe> ) { chomp $data; print STDERR "child $num: [$data] "; } exit; } }; # Parent here $pipe->writer; push @children, $pipe; } # Send some data to the kids for ( 1 .. 20 ) { # pick a child at random my $num = int rand $num_children; my $child = $children[$num]; print $child "Hey there. "; } Daemon example use strict; use Proc::Fork; use POSIX; # One-stop shopping: fork, die on error, parent process exits. run_fork { parent { exit } }; # Other daemon initialization activities. $SIG{INT} = $SIG{TERM} = $SIG{HUP} = $SIG{PIPE} = &some_signal_handler; POSIX::setsid() or die "Cannot start a new session: $! "; close $_ for *STDIN, *STDOUT, *STDERR; # rest of daemon program follows Forking socket-based network server example use strict; use IO::Socket::INET; use Proc::Fork; $SIG{CHLD} = 'IGNORE'; my $server = IO::Socket::INET->new( LocalPort => 7111, Type => SOCK_STREAM, Reuse => 1, Listen => 10, ) or die "Couln't start server: $! "; my $client; while ($client = $server->accept) { run_fork { child { # Service the socket sleep(10); print $client "Ooga! ", time % 1000, " "; exit; # child exits. Parent loops to accept another connection. } } } EXPORTS
This package exports the following symbols by default. o "run_fork" o "child" o "parent" o "retry" o "error" DEPENDENCIES
Carp, which is part of the Perl distribution, and Exporter::Tidy. BUGS AND LIMITATIONS
None currently known, for what that's worth. Please report any bugs or feature requests to "bug-proc-fork@rt.cpan.org", or through the web interface at <https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Proc-Fork>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. AUTHOR
Aristotle Pagaltzis, <mailto:pagaltzis@gmx.de> Documentation by Eric J. Roode. COPYRIGHT AND LICENSE
Copyright (c) 2005-2008 by Aristotle Pagaltzis. All rights Reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic. DISCLAIMER OF WARRANTY
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. perl v5.10.0 2008-09-22 Proc::Fork(3pm)
All times are GMT -4. The time now is 12:55 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy