I am writing a simpel program that can basicly do the same as piping two linux commands can do. For example, ls -l | grep vars.sh, this can be done on the Linux console. I need to write a programm in C that can do the same. I think I got it working but I want to know if I am doing it rite and if there are some modifications I can do on my code.
Here is my code:
#include <stdio.h> // Voor verschillende I/O's, macro's, declaraties.
#include <stdlib.h> // Om de system call te activeren.
#include <unistd.h> // Laden van constanten en types.
int main()
{
pid_t pid;
int pipefd[2];
pipe(pipefd);
pid = fork();
if(pid==-1){
perror("pipe");
exit(EXIT_FAILURE);
}
if(pid>0){
close(pipefd[0]);
dup2(pipefd[1],1);
execlp("ls","ls","-l",NULL);
}
else{
close(pipefd[1]);
dup2(pipefd[0],0);
execlp("grep","grep",".bashrc",NULL);
exit(EXIT_FAILURE);
}
}
Any feedback,rewrites or modifications are welcome.
command | commandthat works on Linux in a C program. The code works, but is there another way to do it by modifying the code? As in can this be done in a other way with C? \$\endgroup\$dup2()a descriptor, you normally want to close the starting descriptor afterwards. \$\endgroup\$