【发布时间】:2018-09-18 00:45:42
【问题描述】:
我不确定为什么会出现段错误。我知道它在我的 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;
}
【问题讨论】:
-
分段错误?是时候将其弹出到您的调试器中并找出原因。找到故障点,然后在此之前逐步检查,看看可能出了什么问题。注意局部变量。
printf调试只能到此为止。 -
你收到
core file了吗?您可以将它与调试器(如 gdb)一起使用来确定故障点。 -
您尝试过 Google 搜索吗?遍历目录是一种非常标准的算法。