我不确定为什么会出现段错误。我知道它在我的pidspec函数中的某个位置,但是我不确定为什么会这样。该程序的目标是将进程ID作为第一个参数传递给程序,从那里开始,pid位于proc文件夹中,并且该文件的内容显示在控制台中。任何帮助将不胜感激。我一年都没写过C了,所以有点生锈。
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <string.h>
void pidspec(char *v){
DIR *myDirectory;
struct dirent *myFile;
char *proc = "/proc";
printf("Made it here");
myDirectory = opendir(proc);
if(myDirectory){
printf("Made it here");
if(strcmp(myFile->d_name, v) == 0){
myDirectory = opendir(v);
if(myDirectory){
while ((myFile = readdir(myDirectory)))
printf("%s\n", myFile->d_name);
}
}
}
return;
}
int main(int argc, char *argv[]){
printf("Made it here");
if(argc == 2){
printf("%s",argv[1]);
pidspec(argv[1]);
}
return 0;
}
答案 0 :(得分:3)
第一次运行时,myFile
未初始化,没有指向任何内容,然后您取消引用它!
struct dirent *myFile;
...
if(strcmp(myFile->d_name, v) == 0)
所以您不是要在这里使用myFile,还是要确保它首先指向某个东西。