gpt4 book ai didi

c - 如何在尝试使用返回权限被拒绝的 popen 函数时处理无效/垃圾值

转载 作者:行者123 更新时间:2023-11-30 15:34:36 24 4
gpt4 key购买 nike

我正在尝试编写一个程序来查找用户拥有的文件。然后将输出打印到变量中以对其进行操作或与其他程序进行通信。问题是当我将目录设置为 / 时,大多数早期查找都会被拒绝权限。但似乎有一个 NULL/垃圾或分配给变量的东西,即使它声明权限被拒绝。代码如下:

static struct{
char file_owned[8192][1024];
}information;

void get_file_owned(char *username)
{
FILE *stream3;
extern FILE *popen();
char command[1024];
char buff[1024];
int i;

sprintf(command, "find / -user %s -ls",username);
if(!(stream3 = popen(command), "r"))){
exit(1);
}
i=0;
while(fgets(buff, sizeof(buff), stream3)!=NULL){
sprintf(information.file_owned[i],"%s",buff); //it print something into file_owned. But I do now know what.
i++;
}
pclose(stream3);
return;
}

int main(int argc, char **argv)
{
static char *username;
int i;

username = "fikrie";
get_file_owned(username);

for(i=0;i<10;i++){
printf("%s\n",information.process_owned[i]);
}
return 0;
}

这是输出:

find: `/proc/1657/task/1659/ns` : Permission denied
find: `/proc/1713/task/1713/ns` : Permission denied
...
...
//There's a lot of this kind of output
...
Segmentation fault(core dumped)

我预计这是由于权限被拒绝引起的。然后它只会将垃圾打印到 process_owned 中。我应该如何处理权限被拒绝的输出?我试图在 get_file_owned 函数中处理 NULL 。但这并不能解决问题。

while(fgets(buff, sizeof(buff), stream3)!=NULL){
if(buff == NULL){
continue;
}
sprintf(information.file_owned[i],"%s",buff);
i++;
}

我还尝试使用 gdb 来查看段错误。这是结果:

warning: Can't read pathname for load map: Input/output error
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0 _IO_getline info (fp=0x9ec50b8, buf=0x2 <Address 0x2 out of bounds>, n=254, delim=10, extract_delim=1, eof=0x0) at iogetline.c:91
iogetline.c: No such file or directory.

请注意,如果我尝试在我的主目录中运行它。 /home/fikrie/Documents。没有段错误或错误。

编辑:我也以 root 身份运行这个程序。将结构方式改为这种类型:

struct{
char file_owned[1024];
}information[1024]; //I tried changing this into 8094 also. Just in case the array for this struct is not enough.

最佳答案

find 可能返回超过 8192 行。因此,while 循环会溢出数组 file_owned

关于c - 如何在尝试使用返回权限被拒绝的 popen 函数时处理无效/垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23211678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com