3 Replies - 386 Views - Last Post: 18 February 2013 - 06:13 AM Rate Topic: -----

#1 codepal   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 17-February 13

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.

#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);
}
}



Is This A Good Question/Topic? 0
  • +

Replies To: Files getting appeneded with undesired data

#2 jimblumberg   User is offline

  • member icon

Reputation: 5492
  • View blog
  • Posts: 17,068
  • Joined: 25-December 09

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
Was This Post Helpful? 0
  • +
  • -

#3 codepal   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 17-February 13

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.
Was This Post Helpful? 0
  • +
  • -

#4 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6221
  • View blog
  • Posts: 21,473
  • Joined: 05-May 12

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
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1