For an assignment, i am supposed to implement the linux terminal. My terminal should support arguments with pipes. Like the user can input: ls | grep ".cpp"
ls | grep ".cpp"
What i have done so far is:
pid = fork();
if(pid==0)
{
close(fd[0]);
dup2(fd[1],1);
close(fd[1]);
execlp("/bin/ls","ls");
}
wait(NULL);
pid=fork();
if(pid==0)
{
close(fd[1]);
dup2(fd[0],0);
close(fd[0]);
execlp("/bin/grep","grep",".cpp");
}
my first child works perfectly, writes the output of ls into a pipe declared earlier, however, my second child runs grep, but it apparently can not get input from pipe. Why is that so? when i run it, my output is /root/OS $ ls | grep
it just gets stuck like this
Don't ignore compiler warnings:
$ gcc lol.c
lol.c: In function ‘main’:
lol.c:14:5: warning: not enough variable arguments to fit a sentinel [-Wformat=]
execlp("/bin/ls","ls");
^
lol.c:23:5: warning: missing sentinel in function call [-Wformat=]
execlp("/bin/grep","grep",".cpp");
^
Here's man execlp
:
The first argument, by convention, should point to the filename associated with the file being executed. The list of arguments must be terminated by a NULL pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL.
Always compile with -Werror
so that compilation fails if there are warnings, and preferably also with -Wall
to get warnings for all potential issues.
Here's your program with a main method and sentinels added:
#include <unistd.h>
#include <sys/wait.h>
int main() {
int fd[2];
int pid;
pipe(fd);
pid = fork();
if(pid==0)
{
close(fd[0]);
dup2(fd[1],1);
close(fd[1]);
execlp("/bin/ls","ls", NULL);
}
wait(NULL);
pid=fork();
if(pid==0)
{
close(fd[1]);
dup2(fd[0],0);
close(fd[0]);
execlp("/bin/grep","grep",".cpp", NULL);
}
return 0;
}
Here's how it runs now:
$ gcc -Wall -Werror lol.c -o lol
$ ./lol
foo.cpp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.