Simple pipe implementation
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
int pfds[2], status;
char *com1[]={"ls","-a",NULL};
char *com2[]={"sort",NULL};
switch(fork()){
case -1:
printf("Error has been occured");
exit(1);
case 0:
break;//Run the child
default:
wait(&status);//Parent is waiting until child exit
return (status);
}
if(pipe(pfds)<0)
exit(1);
switch(fork()){
case -1:
exit(1);
case 0:
close(1);//Close the stdout
dup(pfds[1]);//Duplicate the pipe write end
close(pfds[0]);//Close pipe read end
close(pfds[1]);//Close pipe write end
execvp(com1[0], com1);//Execute the command
exit(1);
default:
close(0);//Close the stdin
dup(pfds[0]);//Duplicate the pipe read end
close(pfds[0]);//Close pipe read end
close(pfds[1]);//Close pipe write end
execvp(com2[0], com2);//Execute the command
exit(1);
}
return 0;
}
#include <unistd.h>
#include <stdlib.h>
int main(){
int pfds[2], status;
char *com1[]={"ls","-a",NULL};
char *com2[]={"sort",NULL};
switch(fork()){
case -1:
printf("Error has been occured");
exit(1);
case 0:
break;//Run the child
default:
wait(&status);//Parent is waiting until child exit
return (status);
}
if(pipe(pfds)<0)
exit(1);
switch(fork()){
case -1:
exit(1);
case 0:
close(1);//Close the stdout
dup(pfds[1]);//Duplicate the pipe write end
close(pfds[0]);//Close pipe read end
close(pfds[1]);//Close pipe write end
execvp(com1[0], com1);//Execute the command
exit(1);
default:
close(0);//Close the stdin
dup(pfds[0]);//Duplicate the pipe read end
close(pfds[0]);//Close pipe read end
close(pfds[1]);//Close pipe write end
execvp(com2[0], com2);//Execute the command
exit(1);
}
return 0;
}
Comments
Post a Comment