2014-04-22 16 views
0

我想寫一個程序,將查找用戶擁有的文件。然後將輸出結果打印到一個變量中進行操作或與其他程序進行交流。問題是當我把目錄作爲/時,大部分早期的查找都會被拒絕。但似乎有一個NULL /垃圾或分配給變量的東西,即使它聲明權限被拒絕。下面是代碼:如何處理無效/垃圾值,而試圖使用popen函數,返回一個權限被拒絕

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. 
+0

** OMG dat struct!** –

+0

ahahaha ..這只是一個例子。只是懶得打字。但我希望這有助於描述我想要做的事情。 –

+0

你是否嘗試以root用戶的身份運行你的程序? – const

回答

1

find propably返回多於8192線。因此while循環溢出數組file_owned

+0

是的。似乎是這樣,因爲它將一些東西分配給struct事件,但是Permission被拒絕了。有沒有辦法讓我不分配任何東西,或者如果文件是Permission denied,就跳過sprintf。 –