Page 1 of 1

*nix open call in C

Posted: Sat Mar 03, 2012 12:52 pm
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?

Re: *nix open call in C

Posted: Sat Mar 03, 2012 7:14 pm
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

Re: *nix open call in C

Posted: Sat Mar 03, 2012 9:15 pm
by avansc
The reason you cant open it without root is because you NEED some sort of privileges set.