#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void main()
{
int fd;
char *path = "/etc/myfile";
int flags = O_RDWR | O_APPEND;
fd = open(path, flags);
sleep(1);
setuid(getuid());
if (fork())
{
close (fd);
exit(0);
}
else
{
write (fd, "Hello World", 11);
close (fd);
}
}
Files getting appeneded with undesired data
Page 1 of 13 Replies - 140 Views - Last Post: 18 February 2013 - 06:13 AM
#1
Files getting appeneded with undesired data
Posted 17 February 2013 - 06:01 PM
I am facing a problem in the following piece of code written by superuser of system. I am trying to read a very important file "myfle" in the system. When I run this program, file not only displays contents but also it prints "Hello World" at the end. I am a beginner in c programming and would appreciate if anyone tell me how the program prints the above output.
Replies To: Files getting appeneded with undesired data
#2
Re: Files getting appeneded with undesired data
Posted 17 February 2013 - 06:22 PM
It prints the data by calling the write() function, after opening the file. If you call this program more than once it should keep adding the "Hello World" to your file.
Jim
Jim
#3
Re: Files getting appeneded with undesired data
Posted 17 February 2013 - 11:29 PM
Hi Jim,
Thanks for your response.
I think, the program should execute the if block and not the else block. I compiled the program using gcc and ran the program as a login user in Linux.I would appreciate if you could tell me why it writes the output.
Thanks for your response.
I think, the program should execute the if block and not the else block. I compiled the program using gcc and ran the program as a login user in Linux.I would appreciate if you could tell me why it writes the output.
#4
Re: Files getting appeneded with undesired data
Posted 18 February 2013 - 06:13 AM
It executes both the success and failure blocks. Read about fork(). In particular, the return values section.
http://linux.die.net/man/2/fork
http://linux.die.net/man/2/fork
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote



|