我是新手。我需要打印系统上所有进程的详细信息。我已将"ps -aux"
的输出重定向到文本文件并按顺序打开以显示。虽然我得到了正确显示的所需细节,但我得到堆栈粉碎错误然后分段错误。我可以理解分段错误来自fgets
/ sscanf
函数之一。我可以知道哪里出错了吗?
if ( NULL != ( FileDesc = fopen( FileName , "r" ) ) )
{
if( ! fgets(buf, sizeof( buf ), FileDesc) )
{
Status = -1;
}
while( NULL != fgets( buf, sizeof( buf ), FileDesc ) )
{
sscanf( buf, "%*s %d %*s %s %*d %*d %*s %s %*s %s %[^\n] ",
&(ProcVar[CurrProcessNum].Pid),
&(ProcVar[CurrProcessNum].Size),
(ProcVar[CurrProcessNum].State),
(ProcVar[CurrProcessNum].CpuTime),
(ProcVar[CurrProcessNum].Cmd));
printf (" PID: %d size: %s State: %s CpuTime: %s Cmd %s",
(ProcVar[CurrProcessNum].Pid),
(ProcVar[CurrProcessNum].Size),
(ProcVar[CurrProcessNum].State),
(ProcVar[CurrProcessNum].CpuTime),
(ProcVar[CurrProcessNum].Cmd));
CurrProcessNum ++;
}
}
示例输出为:
PID: 21342 size: 0.0 State: S CpuTime: 0:00 Cmd [kjournald]
PID: 23384 size: 2.6 State: Sl CpuTime: 39:59 Cmd /opt/Adobe/Reader9/Reader/intellinux/bin/acroread /root/Documents/Comcast_RDK2.0-B13.4_Broadcom_release_notes_20140123.pdf
PID: 23495 size: 0.9 State: Ssl CpuTime: 9:01 Cmd gnome-terminal
PID: 23498 size: 0.0 State: S CpuTime: 0:00 Cmd gnome-pty-helper
PID: 23499 size: 0.0 State: Ss CpuTime: 0:00 Cmd bash
PID: 26733 size: 0.1 State: Ss CpuTime: 0:18 Cmd sshd: root@pts/3
PID: 26843 size: 0.2 State: Ss CpuTime: 0:01 Cmd -bash
PID: 26943 size: 0.1 State: Ss CpuTime: 0:06 Cmd sshd: root@notty
PID: 27052 size: 0.0 State: Ss CpuTime: 0:00 Cmd /usr/lib/openssh/sftp-server
PID: 29510 size: 0.0 State: S CpuTime: 0:00 Cmd su root
PID: 29517 size: 0.1 State: S+ CpuTime: 0:04 Cmd bash
PID: 29951 size: 0.1 State: S+ CpuTime: 1:06 Cmd minicom
PID: 30056 size: 0.0 State: Ss+ CpuTime: 0:00 Cmd bash
PID: 30293 size: 0.0 State: Ss CpuTime: 0:00 Cmd bash
PID: 30329 size: 0.0 State: S+ CpuTime: 0:01 Cmd ssh root@192.168.70.54
PID: 30597 size: 0.0 State: Ss CpuTime: 0:00 Cmd bash
PID: 30632 size: 0.0 State: S+ CpuTime: 0:00 Cmd ssh root@192.168.70.54
PID: 31508 size: 0.0 State: Ss+ CpuTime: 0:00 Cmd bash
PID: 31522 size: 0.1 State: Ss+ CpuTime: 0:00 Cmd bash
*** stack smashing detected ***: bin/TR69_DM terminated
Segmentation fault
答案 0 :(得分:0)
@vonbrand请查看结构字段
struct ProcessInfo {
char ProcName[CHAR_BUF_SIZE];
char Cmd[CHAR_BUF_SIZE];
char CpuTime[CHAR_BUF_SIZE];
int32_t Pid;
int32_t Priority;
char Size[CHAR_BUF_SIZE];
char State[CHAR_BUF_SIZE];
};
答案 1 :(得分:0)
从您显示的代码(这仍然不足以让我们继续使用btw!),您将使用以下任一个(或两者)覆盖堆栈:
ProcVar
数组大小,因为您没有检查数组
边界CurrProcessNum < elements in the array
)CHAR_BUF_SIZE
。要解决这个问题,您可以使用安全版本
sscanf。微软有一个safe sscanf called sscanf_s
在缓冲区参数之后传递缓冲区大小。或者你可以
尝试完全放弃sscanf。或使用更大的缓冲区然后复制
使用安全字符串副本(例如strncpy
)将 放入您的数组中。