大神急救!!!!输入进程号pid,输出进程名pname。运行出现段错误,调试了很久,只想说这是有史以来遇到的最纠结的段错误,莫名其妙!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
void getProcessName(int pid, char *pname)
{
//get process name by shell
char cmd[100]={0};
sprintf(cmd,"readlink /proc/%d/exe >/pname.txt",pid);
system(cmd);
sleep(2);
//open file
int fd=open("/pname.txt" ,O_RDWR);
printf("#####%d\n",fd);
if(fd<0)
{
printf("open():\n");
return;
}
printf("!!!!!");
//read file
if(read(fd,pname,200)<0)
{
perror("read():\n");
return;
}
//close file
if(close(fd)<0)
{
perror("close():");
return;
}
//remove file
system("rm /pname.txt");
}
void main(){
int pid;
char chs[200];
printf("Please input pid: \n");
scanf("%d",pid);
getProcessName(pid, chs);
if(chs)
printf("The name of pid%d is %s: ", pid ,chs);
}
------解决方案--------------------
要学会gdb啊 定位段错误几秒钟的事
scanf("%d",pid);