2017-03-11 34 views
0

C語言編程問題文件權限的子進程

我試着去一個有一個父進程打印一個子進程,每 文件穿過作爲參數,或者如果沒有傳遞參數然後抓住當前每個文件目錄。爲所有文件打印權限。我相信問題是我的struct stat buf的位置; (目前全球)。目前我的輸出打印出文件名和目錄,但沒有權限。任何建議將不勝感激

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <pwd.h> 
#include <sys/stat.h> 
#include <unistd.h> 
#include <string.h> 
#include <dirent.h> 

void permission(); 
typedef int bool; 
#define TRUE 1 
#define FALSE 0 

struct stat buf; 

int main(int argc, char *argv[]) { 
bool commandline = FALSE; //determine if 0 args passed 
if (argc < 2){commandline=TRUE;} 
struct passwd *passwd; 
passwd = getpwuid(getuid()); 
char *file, *dir; 
uid_t uid; //user id 
gid_t gid; //group 
uid = getuid(); 
gid = getgid(); 
DIR *d; 
struct dirent *directory; 
d = opendir("."); 
struct stat buf; 

int i,pid=1; 
for (i = 1; (i < argc && pid) || (commandline==TRUE) ; i++) { 
    if (!(pid = fork())) { 
     if (argc > 1) { 
      dir = passwd->pw_dir; 
      file = malloc(sizeof(dir) + 1 + sizeof(argv[i])); 
      strcat(file, dir); 
      strcat(file, "/"); 
      strcat(file, argv[i]); 
      printf("File: %s\nDirectory: %s\n", argv[i], file); 
      permission(); 
     } else { 
      if (d) { 
       while ((directory = readdir(d)) != NULL) { 
        dir = passwd->pw_dir; 
        printf("File: %s\n",directory->d_name); 
        printf("Directory: %s/%s\n",dir, directory->d_name); 
        permission(); 
       } 
      } 
     } 
    } /* IF CHILD */ 
    commandline=FALSE; 
} /* FOR LOOP */ 
while (wait(NULL) > 0); 

} /* !Main */ 

/* PRINT FILE PERMISSIONS*/ 
void permission() { 
int fileMode; 

fileMode = buf.st_mode; 
if (fileMode & S_IRUSR) { 
    printf("You have Owner permissions:"); 
    if (fileMode & S_IREAD) { printf(" Read "); } 
    if (fileMode & S_IWRITE) { printf("Write "); } 
    if (fileMode & S_IEXEC) { printf("Execute"); } 
    printf("\n\n"); 
} else if (fileMode & S_IRGRP) { 
    printf("You have Group permissions:\n"); 
    if (fileMode & S_IREAD) { printf(" Read "); } 
    if (fileMode & S_IWRITE) { printf("Write "); } 
    if (fileMode & S_IEXEC) { printf("Execute"); } 
    printf("\n\n"); 
} else if (fileMode & S_IROTH) { 
    printf("You have General permissions:"); 
    if (fileMode & S_IREAD) { printf(" Read "); } 
    if (fileMode & S_IWRITE) { printf("Write "); } 
    if (fileMode & S_IEXEC) { printf("Execute"); } 
    printf("\n\n"); 
} 
} 

回答

0

實際上,struct stat buf發生在文件範圍,並作爲main的局部變量。

問題很簡單:您從不打電話stat(2)。當您撥打permission時,您傳遞的是未初始化的緩衝區。顯然,它全部爲零,並且您的if語句都不計算爲真。

每個子進程都有自己的地址空間。無論是本地還是全局定義的buf,它都將顯示在子地址空間中,因爲它是其父項的副本。

+0

你能給我一個關於如何將它傳遞給permission()的示例代碼。 –

+0

我想起了錯誤的樹叫你。你的困難並不是沒有把信息傳遞給你的功能。你的困難在於'buf'沒有數據,因爲你永遠不會用'stat'填充它。 –

0

像James Lowden說的那樣,你的struct stat buf是main的局部變量,目前不能用於你的函數permission()

然後,你必須通過一個「非空」緩衝液,例如,通過0的初始化,然後該程序就可以進入你的if聲明

讓我知道,如果這有助於

+0

我試圖使用(結構統計buf)作爲內部(權限())的一個局部變量,它打印所有者的權限:讀寫執行每次甚至文件我知道沒有這些權限即時通訊有點失去了從哪裏去從這裏的任何線索? –