【问题标题】:File can be opened only by root user..Wrong permissions given, i guess文件只能由root用户打开..我猜给了错误的权限
【发布时间】:2011-01-12 08:02:48
【问题描述】:

我的程序基本上运行一个带有命令行参数的可执行文件。 一个子进程被分叉,子进程的输出被放在文件“filename”中。

问题是制作文件并写入数据但只能由root用户打开.. 如何使其对调用程序的用户可读?

代码是:

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

【问题讨论】:

  • ls -l 指向文件时会说什么?
  • -----xr-- 1 shadyabhi shadyabhi 7342 2010-02-03 01:39 文件名

标签: c linux system-calls file-handling


【解决方案1】:

重新阅读打开的手册页,您没有正确传递文件模式参数并导致标志在过程中被弄乱。

【讨论】:

  • 刚刚将 open() 调用更改为:- open("filename",O_WRONLY|O_EXCL|O_CREAT,777) 问题就解决了......
  • 不要使用 777;那是十进制数,不是八进制数。不要使用 0777;该文件不是可执行的,也不应该是世界可写的。使用 0644 甚至 0444(或者如果您信任属于您小组的其他人,也可以使用 0664)。
  • @Shadyabhi:如果您不喜欢八进制常量,或者使用符号名称,例如S_IRUSER|S_IWUSER|S_IRGRP|S_IWGRP|S_IROTH.
  • 非可执行文件的最佳模式值是0666S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH。提供的模式与用户的 umask 结合以获得最终的权限位。在每个用户都有一个私有组的系统上,默认的 umask 通常是 0002,当有一个用户组时,它通常是 0022。最终的权限则分别为06640644。通常,为用户组和其他指定相同的位,以便用户可以控制最终权限。有关详细信息,请参阅 umask(2) 手册页 (linux.die.net/man/2/umask)。
  • 好的。我懂你。我不应该使用它...thanx 指出来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 2010-12-10
  • 2013-11-18
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
相关资源
最近更新 更多