LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 06-24-2011, 05:15 AM   #1
knobby67
Member
 
Registered: Mar 2006
Posts: 627

Rep: Reputation: 43
C file functions crash unless root


Hi All,
I've encountered a problem when running a simple bit of code, I'm using c to read write data to a binary file. It works fine when I run as root. However when I run as a user it produces the file, however when I try to open / write after it's produced it caused a seg fault. Is there any reason file functions ( fopen etc ) would work for root and not a user and is there a way to fix this?

Thanks
 
Old 06-24-2011, 05:39 AM   #2
Ivshti
Member
 
Registered: Sep 2008
Distribution: Linvo
Posts: 132

Rep: Reputation: 43
Yes, you are not permitted to modify this file unless you are using root. If you want to make a file modifiable by a certain user, use the command chown.
For example,
Code:
chown user:group /tmp/file
If you don't know which group to use, type the username again, because typically there is a group with the same name for every user.
For example, if your file is in the path "/tmp/file", and your username is "knobby67", you use this:
Code:
chroot knobby67:knobby67 /tmp/file
You can prevent segfaults (and instead do error reporting) by checking the return value from the fopen function. If it equals NULL, you can print the error with the following code:
Code:
perror("the error is");
Which will print the last error with a prefix of "the error is". In order to use perror, you must include the stdlib.h header.
 
Old 06-24-2011, 06:15 AM   #3
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Kubuntu, Fedora, RHEL
Posts: 1,541

Rep: Reputation: 335Reputation: 335Reputation: 335Reputation: 335
Quote:
Originally Posted by knobby67 View Post
Hi All,
I've encountered a problem when running a simple bit of code, I'm using c to read write data to a binary file. It works fine when I run as root. However when I run as a user it produces the file, however when I try to open / write after it's produced it caused a seg fault. Is there any reason file functions ( fopen etc ) would work for root and not a user and is there a way to fix this?

Thanks
How did you "produce" the file? Using fopen()? Does your code check to verify that you successfully created the file? If at a later point you attempt to open the file (presumably in another area of your code), did you check to see if the file was successfully opened before assuming it was ok to write to it?
 
Old 06-24-2011, 08:47 AM   #4
MTK358
LQ 5k Club
 
Registered: Sep 2009
Posts: 6,443
Blog Entries: 3

Rep: Reputation: 723Reputation: 723Reputation: 723Reputation: 723Reputation: 723Reputation: 723Reputation: 723
Do you have permissions to read/write the file? Does your code check whether the file was successfully opened before using it?
 
Old 06-24-2011, 08:48 AM   #5
knobby67
Member
 
Registered: Mar 2006
Posts: 627

Original Poster
Rep: Reputation: 43
Quote:
Originally Posted by dwhitney67 View Post
How did you "produce" the file? Using fopen()? Does your code check to verify that you successfully created the file? If at a later point you attempt to open the file (presumably in another area of your code), did you check to see if the file was successfully opened before assuming it was ok to write to it?

yes the file is produced, I can step through code and see it "appear" in the folder. No I don't check when I reopen as the code works fine when I'm root, so if I start with sudo, it's fine. It's only as a user that it seg faults.

Quote:
Originally Posted by Ivshti
use the command chown
Unfortunately I'm producing the file myself inside my C code , so using chown is not really possible, well mybe I could system( but that seems a bit long winded.
 
Old 06-24-2011, 10:03 AM   #6
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Kubuntu, Fedora, RHEL
Posts: 1,541

Rep: Reputation: 335Reputation: 335Reputation: 335Reputation: 335
Quote:
Originally Posted by knobby67 View Post
yes the file is produced, I can step through code and see it "appear" in the folder. No I don't check when I reopen as the code works fine when I'm root, so if I start with sudo, it's fine. It's only as a user that it seg faults.
Please show the fopen() call that you use in your code. I am most interested in seeing a) the filename, and b) the mode used to open the file.
 
Old 06-24-2011, 06:45 PM   #7
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,659
Blog Entries: 4

Rep: Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941Reputation: 3941
Most likely, the file is not accessible to you. Therefore, the fopen() call will return NULL.

If you subsequently use that value, without checking that it is null, a protection exception ("seg fault") will occur, because NULL corresponds to an address of $00000000 ... which is always inaccessible (indeed, for this very reason).

Programs must never "assume that all is well." That's one reason why you should never develop software on high-powered accounts. The software must graciously detect the condition and meaningfully report it to the user.

It is quite handy to use languages that will "throw an exception" when something goes wrong, but "C" is an older language that does not, ordinarily, do that.

Last edited by sundialsvcs; 06-24-2011 at 06:47 PM.
 
Old 06-25-2011, 09:34 PM   #8
lzgonline
LQ Newbie
 
Registered: Jun 2011
Distribution: CentOS 5.5
Posts: 5

Rep: Reputation: Disabled
It seems some problems with the program while creating the file in user mode,check if you have the permission to create file in the program directory in user mode,if not,just give the permission or excute program under the user home directory.

Last edited by lzgonline; 06-25-2011 at 09:35 PM.
 
Old 06-25-2011, 11:27 PM   #9
paulsm4
LQ Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
Hi -
Quote:
Please show the fopen() call that you use in your code. I am most interested in seeing a) the filename, and b) the mode used to open the file.
And *MOST* interested in seeing if you check the error status

1. "Permissions" can cause you to fail to open a file.
2. Failing to open a file *cannot* directly cause a segmentation violation.
... However ...
3. Trying to use a file that you failed to open most definitely CAN and WILL cause an access violation

Q: Do you check for "NULL" in your fopen()?
 
Old 06-26-2011, 06:22 AM   #10
knobby67
Member
 
Registered: Mar 2006
Posts: 627

Original Poster
Rep: Reputation: 43
Hi he's how I write to the file ( eg save data )

Code:
void StoreLastGameValues( LASTGAMERECALL *lastgame )
{
int count=0;
FILE *fp;
	if((fp=fopen("lastgamescorelist", "rb"))==NULL)
	{
		printf("\n DEBUG cannot open last game file\n");		/*no file so close and create*/
		fp=fopen("lastgamescorelist", "w+b");				/*create the file*/
		/********INIT THE ARRAY*****/
		for(count=0;count<11;count++) 
		{			
			LastGameList[count].time=time(NULL);			/*init the array*/
			for( int i = 0; i < 5; i++ ) LastGameList[ count ].position[ i ] = 0;
			fwrite(&LastGameList[ count ],sizeof( LASTGAMERECALL ),1,fp);
		}
		fclose(fp);
		return;
	}

	/*******READ IN DATA********/
	for( count=0; count<10; count++ ) 
	{
		int i = fread(&LastGameList[ count ],sizeof( LASTGAMERECALL ),1,fp);
		if( i == 1 ){ };  //needed for new version of gcc	
	}
	fclose(fp);

        /*mode to top of table*/
	for( count=10 ;count>=0; count-- ) 
	{
		LastGameList[ count+1 ]= LastGameList[ count ];	/*move up one*/
				
	}

	
	LastGameList[ 0 ] = *lastgame;

	/******WRITE DATA FILE***/
	fp=fopen("lastgamescorelist", "wb");
	for( count = 0; count < 11; count++ ) 
	{
		fwrite(&LastGameList[ count ],sizeof( LASTGAMERECALL ),1,fp);	
	}
	fclose(fp);
}

Last edited by knobby67; 06-26-2011 at 06:25 AM.
 
Old 06-26-2011, 07:45 AM   #11
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Kubuntu, Fedora, RHEL
Posts: 1,541

Rep: Reputation: 335Reputation: 335Reputation: 335Reputation: 335
Thanks for the additional information; however it appears that there is still some gray areas.... how is LASTGAMERECALL defined, and how is LastGameList declared?

As for your function, it seems that initially you are checking to see if the file is readable, and hence implying that it exists. If it does not, then you open the file for writing so that you can initialize it with data.

If the file does happen to exist, then you read in all of its data, perform a shuffling of the data, and then re-write that data to the file.

You could have chosen to use stat() to determine if the file exists, and also devise separate functions that read data from the file, write data to the file, initialize the data, and lastly manipulate the data itself. Instead you opted to perform all of these steps (sans stat() call) in one function.

Anyhow, when you have the luxury of time, please answer the questions I posted above.

P.S. The 'b' option used with fopen() is ignored by most POSIX compliant systems, including Linux. It was deprecated long ago.
 
Old 06-26-2011, 09:43 AM   #12
Wim Sturkenboom
Senior Member
 
Registered: Jan 2005
Location: Roodepoort, South Africa
Distribution: Ubuntu 12.04, Antix19.3
Posts: 3,794

Rep: Reputation: 282Reputation: 282Reputation: 282
You do NOT always check if fp is valid (not NULL) after opening the file; e.g. at the end of the shown code under 'write data file'.

You should always check if opening a file succeeded and use e.g. perror() to get the errors in a human readable message.
 
Old 06-26-2011, 10:26 AM   #13
knobby67
Member
 
Registered: Mar 2006
Posts: 627

Original Poster
Rep: Reputation: 43
Quote:
Originally Posted by dwhitney67 View Post
T

Anyhow, when you have the luxury of time, please answer the questions I posted above.

P.S. The 'b' option used with fopen() is ignored by most POSIX compliant systems, including Linux. It was deprecated long ago.
Hi,
sorry if I didn't include what is needed, I think you mean how I first open the the file? This is done as follows
Code:
void InitLastGame( void )
{
int count = 0;
FILE *fp;
	if((fp=fopen("lastgamescorelist", "rb"))==NULL)
	{
		printf("\n DEBUG cannot open last game file\n");		/*no file so close and create*/
		fp=fopen("lastgamescorelist", "w+b");				/*create the file*/
		/********INIT THE ARRAY*****/
		for( count=0; count<11; count++) 
		{			
			LastGameList[ count ].time=time(NULL);		/*init the array*/
			LastGameList[ count ].playerposition[ 0 ] = 0;
			LastGameList[ count ].playerposition[ 1 ] = 0;
			LastGameList[ count ].playerposition[ 2 ] = 0;
			LastGameList[ count ].playerposition[ 3 ] = 0;
			LastGameList[ count ].playerposition[ 4 ] = 0;



			fwrite(&LastGameList[ count ],sizeof(LASTGAMERECALL ),1,fp);
		}
		fclose(fp);
		return;
	}

	/*******READ IN DATA********/
	for(count=0; count < 10 ; count++) 
	{
		int i = fread( &LastGameList[ count ],sizeof(LASTGAMERECALL),1,fp);
		if( i == 1 ){ };	
	}
	fclose(fp);
}
last game is just a structure holding player data

Code:
typedef struct lastgamerecall
{
time_t time;
int playerposition[ 5 ];
long score;

}LASTGAMERECALL;
 
Old 06-26-2011, 10:52 AM   #14
dwhitney67
Senior Member
 
Registered: Jun 2006
Location: Maryland
Distribution: Kubuntu, Fedora, RHEL
Posts: 1,541

Rep: Reputation: 335Reputation: 335Reputation: 335Reputation: 335
It is this variable, LastGameList, that I am interested in seeing how it is declared. I can tell it is a global variable (btw, bad programming practice).

In some loops, you access LastGameList using indexes 0 through 10, in others 0 through 9. How many array slots have you declared for LastGameList.

Also, I've seen the following statement in your code; out of curiosity, why is it present?
Code:
if( i == 1 ){ };
 
Old 06-26-2011, 11:37 AM   #15
theNbomr
LQ 5k Club
 
Registered: Aug 2005
Distribution: OpenSuse, Fedora, Redhat, Debian
Posts: 5,399
Blog Entries: 2

Rep: Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908Reputation: 908
I am surprised no one has suggested trying to open the file with a known-good tool. Since the OP has created a binary-formatted data file, I suggest od:
Code:
od -tx1 lastgamescorelist
This should clarify whether there is a file permissions error, or error in the OP's code.

--- rod.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Firefox crash on actions: File -> open file, bookmarks->Manage->Export mak_mailbox Linux - Desktop 2 09-29-2009 04:17 PM
Functions in .so file not called. priyeshwadhwa Linux - Newbie 2 02-22-2008 04:05 AM
WINE Only Functions Properly as Root Virtuality Linux - Software 1 12-17-2007 04:40 PM
Which File Functions Can Be Used On /proc File? cranium2004 Programming 1 03-06-2005 11:11 AM
every thing in root crash..... TAAN Linux - Hardware 0 09-28-2003 04:39 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 09:10 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration