Sponsored Content
Top Forums Programming pipe() and poll() problem in C Post 302478772 by Corona688 on Thursday 9th of December 2010 12:21:25 AM
Old 12-09-2010
This works:
Code:
#include <stdio.h>
#include <unistd.h>
#include <poll.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	char *args[]={"/bin/tr", "a-z", "A-Z", NULL};
	pid_t pid;
	int run=1;

	int wrpipe[2], rdpipe[2];
	pipe(wrpipe);	pipe(rdpipe);

	pid=fork();
	if(pid < 0)
		return(1);
	else if(pid == 0) // child
	{
		dup2(wrpipe[0], STDIN_FILENO);
		dup2(rdpipe[1], STDOUT_FILENO);

		close(wrpipe[0]);	close(wrpipe[1]);
		close(rdpipe[0]);	close(rdpipe[1]);

		execvp(args[0], args);
		fprintf(stderr, "exec failed\n");
		exit(1);
	}
	else
	{
		struct pollfd p[3];
		char buf_in[512];
		size_t pos_in=0;
		
		// watch stdin
		p[0].fd=STDIN_FILENO;
		p[0].events=POLLIN|POLLHUP;
		p[0].revents=0;

		// watch output pipe
		p[1].fd=wrpipe[1];
		p[1].events=POLLOUT|POLLHUP;
		p[1].revents=0;

		// watch input pipe
		p[2].fd=rdpipe[0];
		p[2].events=POLLIN|POLLPRI|POLLHUP;
		p[2].revents=0;

		close(wrpipe[0]);	close(rdpipe[1]);

		while(run)
		{
			int err=poll(p, 3, 0);

			if(err < 1)
				continue;

			// Events on stdin
			if(p[0].revents & (POLLIN|POLLHUP))
			{
				size_t max=512-pos_in;
				size_t len=read(p[0].fd, buf_in+pos_in, max);

				fprintf(stderr, "stdin read %d bytes\n", len);

				if(len >= 0) pos_in += len;

				// EOF.
				if(len == 0)
				{
					fprintf(stderr, "stdin EOF\n");
					// Write the last data
					write(wrpipe[1], buf_in, pos_in);
					close(wrpipe[1]);
					run=0;	// break the loop
					continue;
				}
			}

			if((p[1].revents & (POLLOUT | POLLHUP)) && pos_in )
			{
				size_t left;
				size_t len=write(p[1].fd, buf_in, pos_in);
				left=pos_in-len;

				fprintf(stderr, "pipe out wrote %d bytes\n", len);

				// Move anything unwritten to the start
				if(left > 0)
					memmove(buf_in, buf_in+len, left);
				pos_in=left;
			}

			if(p[2].revents & (POLLIN | POLLHUP))
			{
				char buf[512];
				size_t len=read(p[2].fd, buf, 512);

				fprintf(stderr, "pipe in read %d bytes\n", len);

				if(len == 0) // EOF
				{
					fprintf(stderr, "pipe in EOF\n");
					// Write the last data
					write(wrpipe[1], buf_in, pos_in);
					close(wrpipe[1]);
					run=0;	// break the loop
					continue;
				}

				write(STDOUT_FILENO, buf, len);
			}
		}

		// Keep reading until eof
		run=1;
		while(run)
		{
			char buf[512];
			size_t len=read(p[2].fd, buf, 512);

			if(len <= 0)
				break;

			fprintf(stderr, "read %d bytes\n", len);

			write(STDOUT_FILENO, buf, len);
		}
	}
}

Code:
$ echo asdf | ./a.out 
stdin read 5 bytes
pipe out wrote 5 bytes
stdin read 0 bytes
stdin EOF
read 5 bytes
ASDF
$

...and the dup2 calls return 0 and 1 respectively.

---------- Post updated at 11:21 PM ---------- Previous update was at 11:06 PM ----------

For OSX, replace /bin/tr with /usr/bin/tr

Otherwise it works fine on OSX
 

10 More Discussions You Might Find Interesting

1. Programming

Wierd pipe problem

I have encountered a strange problem dealing with pipes and forking. The program basicaly does this: cat file | tbl | eqn | groff Now, I have a parent process that forks children that that exec the stuff that they should. The pipes defined in the parent are the ones used. The chain goes... (1 Reply)
Discussion started by: denoir
1 Replies

2. Shell Programming and Scripting

read after pipe problem OSX10.4

I use read often in scripts to filter the right part into a variable like: $ print "abc cde efg" | read k l ; print "k=$k, l=$l" k=, l= This works on linux and unix versions I work with. On OSX 10.4 this doesn't work. I found a workaround but would like to know why the original line... (5 Replies)
Discussion started by: relyveld
5 Replies

3. Shell Programming and Scripting

Problem with pipe into sed

Basically I am trying to write a short script to report total space used on /u0? file systems. This is what I was trying to do:df -k /u0? | grep -v kbytes | awk '{ printf $2 "+" }' | sed s/.$// | bcBut it returns no output. This works however: > A=`df -k /u0? |grep -v kbytes | awk '{ printf $2... (2 Replies)
Discussion started by: 98_1LE
2 Replies

4. Programming

Pipe Problem

Is there a way to know whether is pipe is opened in read or write mode.I mean is there any signal that is generated when a pipe is opened in read or write mode. If you have some solution .please let me know ........ (2 Replies)
Discussion started by: vivivo2000
2 Replies

5. Programming

Problem in read() from a pipe

Hi, Can any one please help me with this. Am struggling hard to get a solution. I am doing telnet through a C program and getting the stdout file descriptor of the remote machine to pipe. read() function is getting data, But whenl it receives SOH character ie. ^A ( Start of heading = Console... (2 Replies)
Discussion started by: JDS
2 Replies

6. Programming

Pipe problem

Could anyone tell me whats wrong whit this piping? the commands that they execute are correct. the command I am trying is ls|wc. Both processes go to the right if statement. for(i=0;i<argc;i++){ if(i==0&&argc>1){//first command if(pipe(pipa1)==-1) ... (2 Replies)
Discussion started by: isato
2 Replies

7. Shell Programming and Scripting

problem using a pipe to grep

Hello ! I want to process a text file in order to extract desired data using sed and grep... Now I am facing a problem piping to grep... nothing happens.. The text consists of blocks of 3 lines that may (or not) contain the Desired data. the desired data is on each 2... (4 Replies)
Discussion started by: ShellBeginner
4 Replies

8. UNIX for Dummies Questions & Answers

problem with pipe operator

hi i am having issues with extra pipe. i have a data file and i need to remove the extra pipe in the(example 4th and 7thline) in datafile. there are many other line and filed like this which i need to remove from files. The sample data is below: 270 31|455004|24/03/2010|0001235|72 271... (3 Replies)
Discussion started by: abhi_n123
3 Replies

9. Shell Programming and Scripting

The problem of pipe

Hi,guys: I want to use c to implement a pipe. For example: ps auxwww | grep fred | more I forked three child processes. Each is responsible for each command, and pipe to next one. for(i=0;i<2;i++) pipe(fd) if(child==1) // child 1 { close(1) dup2(fd,1) close(fd) }... (3 Replies)
Discussion started by: tomlee
3 Replies

10. Programming

Problem with Pipes => Only works first pipe

Hi! I'm having problems with pipes... I need comunnications with childs processes and parents, but only one child can comunnicate with parent (first child), others childs can't. A brief of code: if(pipe(client1r)<0){ perror("pipe"); } ... (1 Reply)
Discussion started by: serpens11
1 Replies
TEE(2)							     Linux Programmer's Manual							    TEE(2)

NAME
tee - duplicating pipe content SYNOPSIS
#define _GNU_SOURCE #include <fcntl.h> ssize_t tee(int fd_in, int fd_out, size_t len, unsigned int flags); DESCRIPTION
tee() duplicates up to len bytes of data from the pipe referred to by the file descriptor fd_in to the pipe referred to by the file descriptor fd_out. It does not consume the data that is duplicated from fd_in; therefore, that data can be copied by a subsequent splice(2). flags is a series of modifier flags, which share the name space with splice(2) and vmsplice(2): SPLICE_F_MOVE Currently has no effect for tee(); see splice(2). SPLICE_F_NONBLOCK Do not block on I/O; see splice(2) for further details. SPLICE_F_MORE Currently has no effect for tee(), but may be implemented in the future; see splice(2). SPLICE_F_GIFT Unused for tee(); see vmsplice(2). RETURN VALUE
Upon successful completion, tee() returns the number of bytes that were duplicated between the input and output. A return value of 0 means that there was no data to transfer, and it would not make sense to block, because there are no writers connected to the write end of the pipe referred to by fd_in. On error, tee() returns -1 and errno is set to indicate the error. ERRORS
EINVAL fd_in or fd_out does not refer to a pipe; or fd_in and fd_out refer to the same pipe. ENOMEM Out of memory. VERSIONS
The tee() system call first appeared in Linux 2.6.17. CONFORMING TO
This system call is Linux-specific. NOTES
Conceptually, tee() copies the data between the two pipes. In reality no real data copying takes place though: under the covers, tee() assigns data in the output by merely grabbing a reference to the input. EXAMPLE
The following example implements a basic tee(1) program using the tee() system call. #define _GNU_SOURCE #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <limits.h> int main(int argc, char *argv[]) { int fd; int len, slen; if (argc != 2) { fprintf(stderr, "Usage: %s <file> ", argv[0]); exit(EXIT_FAILURE); } fd = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd == -1) { perror("open"); exit(EXIT_FAILURE); } do { /* * tee stdin to stdout. */ len = tee(STDIN_FILENO, STDOUT_FILENO, INT_MAX, SPLICE_F_NONBLOCK); if (len < 0) { if (errno == EAGAIN) continue; perror("tee"); exit(EXIT_FAILURE); } else if (len == 0) break; /* * Consume stdin by splicing it to a file. */ while (len > 0) { slen = splice(STDIN_FILENO, NULL, fd, NULL, len, SPLICE_F_MOVE); if (slen < 0) { perror("splice"); break; } len -= slen; } } while (1); close(fd); exit(EXIT_SUCCESS); } SEE ALSO
splice(2), vmsplice(2), feature_test_macros(7) COLOPHON
This page is part of release 3.25 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at http://www.kernel.org/doc/man-pages/. Linux 2009-09-15 TEE(2)
All times are GMT -4. The time now is 08:35 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy