*nix open call in C

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
ajtgarber
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 97
Joined: Wed Jun 10, 2009 8:56 am

*nix open call in C

Post by ajtgarber »

Code: Select all

/*
	File:        lifeping.c
	Description: This application tells a set server (192.168.1.20) at certain intervals that
		     it is indeed still alive.
	Interval:    About 5 minutes
	Port:        2024
	Protocol:    <connect>, send identification code, send status, <terminate>
*/

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <string.h>

#define ID_BILL 0
#define ID_JACOB 1

#define ID ID_BILL

int check_status();

int main(int argc, char* argv[]) {
	//...
}

int check_status() {
	int val = fork();

	int fd = open("status.tmp", O_CREAT | O_RDWR | O_TRUNC);
	if(fd < 0) {
		fprintf(stderr, "Couldn't open file!\n");
	}

	if(val == 0) {
		if(dup2(fd, STDOUT_FILENO) < 0) fprintf(stderr, "dup2 failed\n");
		int val = execve("../isup.sh", NULL, NULL);
		fprintf(stderr, "Something has gone horribly wrong, exec has returned!\n");
	} else {
		int status;
		waitpid(-1, &status, 0);
		if(status != 0) {
			fprintf(stderr, "Something has gone wrong checking status!\n");
		}
	}

	close(fd);
	return -1;
}
When I run this code without root it complains about not being able to open the file (status.tmp), but the file is created
with no privileges whatsoever.
---------- 1 billserver billserver 0 2012-03-03 13:43 status.tmp
However when I run it with root, my program is able to open the file and act normally.
(This code isn't yet finished, at some point it is going to read the contents of the file and return a value based off of that).
Why is it unable to open/create the file without root privileges?
tappatekie
Chaos Rift Junior
Chaos Rift Junior
Posts: 204
Joined: Mon Nov 21, 2011 3:01 pm
Current Project: Web browser from scratch
Favorite Gaming Platforms: SNES, PSP, PS1 and 3
Programming Language of Choice: C#
Location: A house near me
Contact:

Re: *nix open call in C

Post by tappatekie »

At a guess... But maybe it's bitching about it not being the full path of that file e.g "C:\status.tmp".

As I said, its only a guess but my code usually does it sometimes and fixed it right up with that :P
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: *nix open call in C

Post by avansc »

The reason you cant open it without root is because you NEED some sort of privileges set.
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
Post Reply