-
Process and Pipes
I have to create a pipe which simulates the shell command " ps -aux | sort -n | head -10 "
For one pipe the code would be like this:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
int pid, fd[2], ret;
pipe(fd);
pid = fork();
if (pid==0) {
dup2(fd[1], STDOUT_FILENO);
close(fd[0]);
close(fd[1]);
ret = execlp ("ps", "ps", "-aux", NULL);
} else {
dup2(fd[0], STDIN_FILENO);
close(fd[0]);
close(fd[1]);
ret=execlp("sort", "sort", "-n", NULL);
}
return 0;
}
But don't know how to do that with two pipes??
Can anybody help me please?
-
You might want to look at popen. It will probably do just what you want a lot easier.
Jim
-
We are not allowed to use popen or system...
-
Well if you had two pipes, say called p1 and p2 (and not something like fd), then the sort command would dup2 the write end of one of them, and dup2 the read end of the other one.
-
But were do I have to write the second pipe into the "else" branch?
-
Well the else (the parent) needs another fork() because it has another child process to spawn (head -10)
Basically, same again.
-
Ok but after I created another fork() do I still have just 2 branches or do I have to make four now?
Like:
Code:
pid1 = fork();
pid2 = fork();
if (pid1==0) {
dup2(fd[1], STDOUT_FILENO);
close(fd[0]);
close(fd[1]);
ret = execlp ("ps", "ps", "-aux", NULL);
} else {
dup2(fd[0], STDIN_FILENO);
close(fd[0]);
close(fd[1]);
ret=execlp("sort", "sort", "-n", NULL);
}
if (pid2 = 0) {
...
...
} else {
...
...
}
???
-
No, the else you have at present needs a copy of everything you have at present
Code:
pipe()
fork()
if ( p == 0 ) {
// dup(), and run a process
} else {
pipe()
fork()
if ( p == 0 ) {
// dup(), and run a process
} else {
// dup(), and run another
}
}
-
Ok changed my code no, looks like this:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
int ret;
int pid, pid2;
int fd1[2];
int fd2[2];
pipe(fd1);
pid = fork();
if (pid == 0) {
dup2(fd1[1], STDOUT_FILENO);
close(fd2[0]);
close(fd1[0]);
close(fd2[1]);
ret = execlp("ps", "ps", "-aux", NULL);
}
else {
pipe(fd2);
pid2 = fork();
if (pid2 == 0) {
dup2(fd1[0], STDIN_FILENO);
dup2(fd2[1], STDOUT_FILENO);
close(fd1[1]);
close(fd2[0]);
ret = execlp("head", "head", "-10", NULL);
}
else {
dup2(fd2[0], STDIN_FILENO);
close(fd1[1]);
close(fd2[0]);
close(fd1[0]);
ret = execlp("sort", "sort", "-n", NULL);
}
}
return 0;
}
But it doesn't work what's my mistake??
-
Look carefully at what you're closing.