Reputation: 65
This is a correction for an assignment I got, the assignment is the emulate the command who|grep
in a C program. When I tested it, it worked as expected.
From my knowledge, when fork is called, the two processes (child and parent) run in the same time simultaneously, what I don't understand, what makes the commands get executed in the right order, is it necessary to have data available in the pipe FD
so execlp('wc', 'wc', NULL)
get executed? Will it be blocked till data is received from the son process ?
int fd[2], n;
if(pipe(fd) == -1){
perror("Pipe creation failed");
exit(1);
}
n = fork();
if(n == -1){
perror("Fork error");
exit(2);
}
else if(n == 0){ //son
close(1);
dup(fd[1]);
close(fd[1]);
close(fd[0]);
execlp("who", "who", NULL);
}else{
close(0);
dup(fd[0]);
close(fd[0]);
close(fd[1]);
execlp("wc", "wc", NULL);
}
From what I found in man 7 pipe
section I/O on pipes and FIFOs :
If a process attempts to read from an empty pipe, then read(2) will block until data is available. If a process attempts to write to a full pipe (see below), then write(2) blocks until sufficient data has been read from the pipe to allow the write to complete. Nonblocking I/O is possible by using the fcntl(2) F_SETFL operation to enable the O_NONBLOCK open file status flag.
Does this apply still on functions like execlp that gets input from FD
Upvotes: 2
Views: 60