Socketpair() and dup2() question

R. Olivaw daneel at cory.Berkeley.EDU
Fri Mar 10 16:17:24 AEST 1989


Hi! I've been trying to solve this problem I am having for the last
2 weeks and I haven't been able to get anywhere, so please help me.
Basically I have a program written by somebody else which takes
normal stdin and stdout and stderr, however, I need to write some
interface which will take over the job of these std??? for this program
sorta like a master-slave terminal.
The program below I thought would do it, but I have been able to
"write" to the stdin of the program (called "client") below but haven't
been able to read from it's stdout.  
I've asked several people, but they have not been able to reply to the 
question.
Please reply to this account if you can!! THANX A BUNCH!

[Daneel]
#################################CUT HERE###############################

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <stdio.h>
#include <strings.h>
#include <signal.h>
#include <errno.h>

int child;
int sv[2];

/* CHILD interrupt kill process */

killChild()
{
    if ( kill(child, SIGKILL) != 0 ) 
	perror("Kill");
    exit(0);
}

void sendmsg()
{
	char buf[80];
	int nb;

	while (1) {
	write(1, "testing1\n", 9);
	nb = read(0, buf, 10);
	fprintf(stderr, ">>> %s (%d)\n", buf, nb);
	}
}
/*  */
main(argc, argv)
     int argc;
     char **argv;
{

    if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0 )
	error("Opening stream socket pair", 1);

    child = fork();
    switch( child ) {
	/* refer IPC Adv. PS1:8-26*28  */
    case -1:
	error("fork child", 1);
    case 0:			/* this is child */

	error(simulator,4);
	if (close(sv[0])==-1) perror("closing sv[0] in child");
	if (dup2(sv[1], 0)==-1) perror("dup2(1,0)");		/* stdin */
	if (dup2(sv[1], 1)==-1) perror("dup2(1,1)");		/* stdout */
	if (execlp("client", "client", 0) == -1) 
	    error("Can't execute", 1);
	break;			/* this is never reached, i hope */

    default:		
	signal(SIGINT, killChild); /* set up INT to call killChild */
	if (close(sv[1])==-1) perror("closing sv[1] in parent");
	if (dup2(sv[0], 0)==-1) perror("dup2(0,0)");		/* stdin */
	if (dup2(sv[0], 1)==-1) perror("dup2(0,1)");		/* stdout */
	if (close(sv[0])==-1) perror("closing sv[0] in parent");
	break;
    }
	sendmsg();
}   



error( str, type ) 
     char *str;
     int type;
{
    fprintf(stderr, "%s\n", str);
    if (type < 2) exit(type);
}



More information about the Comp.unix.wizards mailing list