I can't be sure without seeing your actual output but the likeliest explanation is that
27017 appears in different places. Your first command will list files for the process with PID
5253, then prints all lines that contain
27017 anywhere in the line.
Your second command will print all open files and then, again, you are selecting all lines that contain
27017 anywhere in the line. I assume you are actually grepping for
27017 in the second command as well and not for
16062 as you show in your question.
In any case, neither of your commands is looking specifically at port
27017. In fact, I don't even see why you expect that a port will be listed.
lsof looks at files, not ports. No ports are shown when I look for
ssh in the output of
lsof -n on my system for example.
Anyway, to give you a more concrete example:
$ sudo lsof -np 7033 | head
lsof: WARNING: can't stat() fuse.gvfsd-fuse file system /run/user/1000/gvfs
Output information may be incomplete.
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
firefox 7033 terdon cwd DIR 8,6 491520 16646145 /home/terdon
firefox 7033 terdon rtd DIR 8,7 548864 2 /
firefox 7033 terdon txt REG 8,7 143680 1841618 /opt/firefox/firefox
firefox 7033 terdon DEL REG 0,30 10335506 /tmp/.glT5RaDf
firefox 7033 terdon mem REG 8,7 12303504 1573445 /usr/share/fonts/truetype/unifont/unifont.ttf
firefox 7033 terdon DEL REG 0,4 970489906 /SYSV00000000
firefox 7033 terdon mem REG 8,7 7470672 540090 /usr/lib/x86_64-linux-gnu/gstreamer-0.10/libgstffmpeg.so
firefox 7033 terdon mem REG 8,7 5177387 1580807 /usr/share/fonts/truetype/wqy/wqy-microhei.ttc
firefox 7033 terdon mem REG 8,7 120688 532953 /usr/lib/x86_64-linux-gnu/gstreamer-0.10/libgstvideoscale.so
Your search for
27017 could match in any of the fields. It could be the size, or the PID or the node or whatever. It could also be part of another number. For example:
$ printf "12345\n12" | grep 12
As you can see above,
12 is matched on both lines, not only on the second where it forms a word. You can use the
-w switch to make
grep match against whole words only:
$ printf "12345\n12" | grep -w 12
So, since you are not restricting the output by PID in the second command, your two
greps could be matching anywhere at all on each line so, of course, you have different output.