views:

65

answers:

1

My program basically runs a executable file with command line arguments. A child process is forked and the output of the child process is taken in the file "filename".

The problem is that the file is made and the data is written but it can only be opened by the root user.. How can make it readable to the user who invoked the program?

The code is:-

    #include<stdio.h>
    #include<string.h>      //strcpy() used
    #include<malloc.h>      //malloc() used
    #include<unistd.h>      //fork() used
    #include<stdlib.h>      //exit() function used
    #include<sys/wait.h>    //waitpid() used
    #include<fcntl.h>

    int main(int argc, char **argv)
    {
char *command;
char input[256];
char **args=NULL;
char *arg;
int count=0;
char *binary;
pid_t pid;
int fdw;

printf("Enter the name of the executable(with full path)");
fgets(input,256,stdin);

command = malloc(strlen(input));
strncpy(command,input,strlen(input)-1);

binary=strtok(command," ");
args=malloc(sizeof(char*));

args[0]=malloc(strlen(binary)+1);
strcpy(args[0],binary);

while ((arg=strtok(NULL," "))!=NULL)
{
    if ( count%10 == 0) args=realloc(args,sizeof(char*)*10);
    count++;
    args[count]=malloc(strlen(arg));
    strcpy(args[count],arg);
}
args[++count]=NULL;

if ((fdw=open("filename",O_WRONLY|O_EXCL|O_CREAT|0700)) == -1)
    perror("Error making file");
close(1);
dup(fdw);

if ((pid = fork()) == -1)
{
    perror("Error forking...\n");
    exit(1);
}
if (pid == 0)   execvp(args[0],&args[0]);
else
{
    int status;
    waitpid(-1, &status, 0);
}
return 0;
}
+3  A: 

Re-read the manpage for open, you are not passing the file mode argument correctly and causing the flags to be messed up in the process.

Geoff Reedy
Ohh.. that was so silly.... thanx...
shadyabhi
shadyabhi
Don't use 777; that's a decimal number, not octal. Don't use 0777; the file is not intended to be executable, and should probably not be world-writable either. Use 0644 or even 0444 (or perhaps 0664 if you trust the rest of the people who belong to your group).
Jonathan Leffler
@Shadyabhi: Or use symbolic names if you don't like octal constants, e.g. `S_IRUSER|S_IWUSER|S_IRGRP|S_IWGRP|S_IROTH`.
ephemient
The best value for mode for a non-executable file is `0666` or `S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH`. The provided mode is combined with the user's umask to get the final permission bits. On systems where each user has a private group, the default umask is usually `0002` when there is a single users group it is usually `0022`. The final permissions are then `0664` and `0644` respectively. In general, specify the same bits for user group and other so the user has control over the final permissions. See the umask(2) manpage (http://linux.die.net/man/2/umask) for more details.
Geoff Reedy
Ok. i got u. I should not use it... thanx for pointing it out.
shadyabhi