C编程问题
Im trying to a have a parent process print a child process for every file passed through as argument or if no arguments are passed then grab every file in the current directory. For all the files print permissions. I believe the problem is the location of my struct stat buf; (currently global). Currently my output prints out the file name and directory but not the permission. Any advice would be greatly appreciated
#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");
}
}
最佳答案
实际上,struct stat buf
出现在文件范围内,并作为 main
的局部变量。
问题很简单:你永远不会调用stat(2)。当您调用permission
时,您正在传递一个未初始化的缓冲区。显然,它全是零,并且您的 if
语句的计算结果都不为 true。
每个子进程都有自己的地址空间。无论buf是本地定义的还是全局定义的,它都会出现在子地址空间中,因为它是其父地址空间的副本。
关于c - 子进程的文件权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42731785/