Re: Communication

>I want to layer my application on top of ssh, but I am not sure how to
>open a program read/write. Thinking IPC was the only way I have been
>trying to unstand how I might accomplish what I need to do in that way.
>I know you can do either read, or write with popen, but not both.

There are probably a few things here that could be improved. To use
this, first call pipe(2) up to 3 times. The program that you fork&exec
will be setup with its stdout, stdin and stderr set to the pipes you
supply. for any that you do not supply, they will remain at whatever
they would be by default. oh, if errpipe is not supplied, stderr is
sent to stdout.

This is all standard "advanced" unix/posix programming. check out
books by stevens on the subject.


    Copyright (C) 1994-2000 Paul Barton-Davis 

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

forkexec (char **argv, char **envp, 
	  int outpipe[2], 
	  int inpipe[2], 
	  int errpipe[2])

#define READ_DESC 0
#define WRITE_DESC 1

	pid_t pid;

	if ((pid = fork ()) == 0) {

		/* In the child process */

		if (inpipe) {
			if (inpipe[READ_DESC] != 0) {
				close (0);
				if (dup (inpipe[READ_DESC]) < 0) {
					return (-1);
			if (inpipe[WRITE_DESC]) {
				close (inpipe[WRITE_DESC]);

		if (outpipe) {
			if (outpipe[WRITE_DESC] != 1) {
				close (1);
				if (dup (outpipe[WRITE_DESC]) < 0) {
					return (-2);
			if (!errpipe) {
				if (dup (outpipe[WRITE_DESC]) < 0) {
					return (-3);
			if (outpipe[READ_DESC]) {
				close (outpipe[READ_DESC]);

		if (errpipe) {
			if (errpipe[WRITE_DESC] != 1) {
				close (2);
				if (dup (errpipe[WRITE_DESC]) < 0) {
					return (-4);
			if (errpipe[READ_DESC]) {
				close (errpipe[READ_DESC]);

		/* do it */

		execvp (argv[0], argv);
		return (-3);
	} else if (pid == -1) {
		return (-5);

	} else {
		/* In the parent process */
		if (outpipe && outpipe[WRITE_DESC]) {
			close (outpipe[WRITE_DESC]);
			outpipe[WRITE_DESC] = -1;

		if (errpipe && errpipe[WRITE_DESC]) {
			close (errpipe[WRITE_DESC]);
			errpipe[WRITE_DESC] = -1;

	return (pid);

[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]