hi i am a student and just start learning low level c programming.i tried to understand read() and write() methods with this program.
#include <unistd.h>
#include <stdlib.h>
main()
{
char *st;
st=calloc(sizeof(char),2);//allocate memory for 2 char
read(0,st,2);
write(1,st,2);
}
i was expecting that it would give segmentation fault when i would try to input more than 2 input characters.but when i execute program and enter ” asdf ” after giving ” as ” as output it executes “df” command.
i want to know why it doesn’t give segmentation fault when we assign more than 2 char to a string of size 2.and why is it executing rest(after 2 char)of input as command instead of giving it as output only?
also reading man page of read() i found read() should give EFAULT error,but it doesn’t.
I am using linux.
Your
readspecifically states that it only wants two characters so that’s all it gets. You are not putting any more characters into thestarea so you won’t get any segmentation violations.As to why it’s executing the
dfpart, that doesn’t actually happen on my immediate system since the program hangs around until ENTER is pressed, and it appears the program’s I/O is absorbing the extra. But that immediate system is Cygwin – see update below for behaviour on a “real” UNIX box.And you’ll only get
EFAULTifstis outside your address space or otherwise invalid. That’s not the case here.Update:
Trying this on Ubuntu 9, I see that the behaviour is identical to yours. When I supply the characters
asls, the program outputsasthen does a directory listingThat means your program is only reading the two characters and leaving the rest for the “next” program to read, which is the shell.
Just make sure you don’t try entering:
(no, seriously, don’t do that).