\"fork() - exec()\" vs \"sockets\"
Nagesh Pabbisetty
Pabbisetty.henr at xerox.com
Sat Mar 11 02:53:05 AEST 1989
Hello Folks,
I have written a small program using fork() and exec(). I am told that I
can achieve the same effect using sockets!! Would anyone tell me how to
modify this code to use sockets ? I am running SunOS 4.0 on a Sun3/60.
Are there instances when using sockets is advantageous than using fork() -
exec() combination ? Any help in this regard would be appreciated.
Thanks...
Nagesh
716-427-1827 / 5458
----------------------------------------------------------
# include <stdio.h>
# include <sys/wait.h>
# define R 0
# define W 1
#define IS_BELL 1
#define NOT_BELL 0
main()
{
int fork(), p[2], q[2] ;
FILE *writeptr,*readptr ;
char buffer[200];
int i = 0;
if (pipe(p) == -1)
perror("pipe(p) failed\n");
if (pipe(q) == -1)
perror("pipe(q) failed\n");
switch(fork()) {
case 0: /* child process */
close(p[W]);
close(R);
dup(p[R]);
close(p[R]);
close(q[R]);
close(W);
dup(q[W]);
close(q[W]);
execlp("/usr/new/xns/xnsftp","xnsftp",0);
perror("exec failed\n");
exit (1);
case -1: /* unsuccesful fork */
perror("fork failed\n");
exit (1);
default: /* parent process */
close(p[R]);
close(q[W]);
writeptr = fdopen(p[W],"w");
readptr = fdopen(q[R],"r");
(void) fprintf(writeptr, "open maya1\n");
(void) fflush(writeptr);
(void) fgets(buffer, 200, readptr);
(void) fprintf(stderr,"%s\n", buffer);
(void) fprintf(writeptr, "bell\n");
(void) fflush(writeptr);
(void) fgets(buffer, 200, readptr);
(void) fprintf(stderr,"%s\n", buffer);
(void) fprintf(writeptr, "dir\n");
fflush(writeptr);
while ( get_inp_str(buffer,readptr) != IS_BELL)
(void) fprintf(stderr, "%s", buffer);
(void) fprintf(writeptr, "quit\n");
(void) fflush(writeptr);
(void) fgets(stdout, 200, readptr);
(void) fprintf(stdout,"%s\n", buffer);
(void) fclose(writeptr);
(void) fclose(readptr);
(void) wait((union wait *)0);
}
}
int get_inp_str(buf, readptr)
char *buf;
FILE *readptr;
{ char c;
int i = 0;
while((c=fgetc(readptr)) != EOF) {
if (c == '\n') {
buf[i++] = c;
buf[i] = '\0';
return NOT_BELL;
}
else if (c == '\007') {
buf[i] = '\0';
return IS_BELL;
}
else buf[i++] = c;
}
}
Following is a synopsis of the algorithm I am using:
The parent process forks. In the child process, xnsftp is execed. The pipe
'p' is used to send commands from the parent to the xnsftp process. Pipe
'q' is used by the parent to read output from the child/xnsftp process.
More information about the Comp.unix.questions
mailing list