1
#include <unistd.h> // for close, fork
#include <stdio.h>
#include <fcntl.h> // for open

int main()
{
    char *argv[2];
    argv[0] = "cat";
    argv[1] = 0;
    if (fork() == 0)
    {
        close(0);
        open("input.txt", O_RDONLY);
        execvp("cat", argv);
    }
}

input.txt is:

Hello
I
am
Sam

But, when I run this code, the output is

Hello
I
am

Thus, not printing the last line of input.txt

Can someone explain the reason for this I am quite new to OS.

  • Cannot reproduce; in my case all lines are printed. I am running it on Mac OS. – MMZK1526 Aug 10 '22 at 08:53
  • @MMZK1526 I was running this on VS code and I encountered this issue, then I ran it directly from the terminal and I got the desired output, is this some issue with VS Code? – Vedanta Mohapatra Aug 10 '22 at 08:57
  • Could be, that would be harder to debug. Do you know what commands are used when you ran it via vsc? Also I don't think that's the issue, but is there anything about newline (\n vs \r\n)? – MMZK1526 Aug 10 '22 at 08:58
  • gcc cat.c -o cat was used when running in VSCode, and even when I used clang here in the VSCode Terminal, I encountered the same issue. Could you mention what you mean by your second question? – Vedanta Mohapatra Aug 10 '22 at 09:04
  • So on Windows, a newline is encoded with "\r\n", while on UNIX it's just "\n". But I don't think that's causing the problem here. Are you sure the "terminal" in vsc is not hiding something? Can you try to pipe the output to another file and check it manually? – MMZK1526 Aug 10 '22 at 09:06
  • @MMZK1526 I am using MacOS – Vedanta Mohapatra Aug 10 '22 at 09:07
  • Does your file end with a newline? – Shawn Aug 10 '22 at 09:10
  • And if you're doing this on a Mac, why is this tagged linux and xv6? – Shawn Aug 10 '22 at 09:11
  • @Shawn Nope. My mistake, the code which I have written here is from xv6 book. So, I mentioned that. As for linux, it was a mistake, I should have tagged UNIX, and macOS. – Vedanta Mohapatra Aug 10 '22 at 09:14
  • 2
    If the file doesn't end with a newline, whatever vs code is using to display output might be waiting for one before actually displaying that last line. – Shawn Aug 10 '22 at 09:15
  • @Shawn Yeah, that solved the problem. But, can you mention why VSCode is waiting for the newline, but the terminal is not? – Vedanta Mohapatra Aug 10 '22 at 09:16
  • Poorly written program? – Shawn Aug 10 '22 at 10:25

0 Answers0