2

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

  • 1
    The answer is yes. – kaylum Dec 24 '19 at 04:41
  • @kaylum can you tell me then please, what's making this not execute as expected: https://pastebin.com/1Z9Hb2c1 I used the same logic as the first one, but apparently the `WC` is not getting any input from `grep`. Ps: in this one, I'm trying to replicated the command `ps -aux | grep root | wc -l` – Abdessalem Boukil Dec 24 '19 at 04:58
  • 3
    `execlp` doesn't read anything from an open file, and doesn't wait. However, _this_ `execlp` runs the program `wc` with no arguments other than the standard `argv[0]` -- and _that program_ reads its standard input aka fd 0, which is (the read side of) the pipe, and thus blocks. Also in C (and C++) `'x'` is a character literal and more than one character is nonportable while `"xyz"` is a string literal and can be multiple characters. (This differs from shells, perl, php, and python, where both `'` and `"` can be used for strings.) – dave_thompson_085 Dec 24 '19 at 05:28
  • @dave_thompson_085 Thanks for tips, can you put it in an answer so I can mark it as answered. And if you can, can you check the code I shared in the previous comment, thanks! – Abdessalem Boukil Dec 24 '19 at 05:39

0 Answers0