这里的代码出现段错误。
gdb :
Program received signal SIGSEGV, Segmentation fault.
_IO_fgets (buf=0x601080 <rc> "", n=100, fp=0x0) at iofgets.c:50
50 iofgets.c: No such file or directory.
代码:
#include <unistd.h>
#include <stdio.h>
char rc[100];
FILE *fp;
int status;
void main() {
fp = popen("sudo lshw |", "grep UUID");
if (fp == NULL)
printf("NULL pointer");
while (fgets(rc, 100, fp) != '\0')
printf("%s", rc);
status = pclose(fp);
if (status == -1) {
printf("pclose error");
/* Error reported by pclose() */
} else{
printf("Unknown error");
}
//return 0;
}
我猜是空指针?我尝试了给出的解决方案,但没有奏效。我猜这是个愚蠢的错误
抱歉,shell 命令将执行 sudo dmidecode | grep UUID
最佳答案
这是错误的
fp = popen("sudo lshw |", "grep UUID");
也许你的意思是,阅读 popen()
fp = popen("sudo lshw | grep UUID", "r");
调用失败,但即使您检查了 fp == NULL
,你继续导致未定义的行为,并导致段错误,fp == NULL
检查需要中止程序,像这样
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
char rc[100];
FILE *fp;
int status;
fp = popen("sudo lshw | grep UUID", "r");
if (fp == NULL)
{
printf("error:%d: %s", errno, strerror(errno));
return -1;
}
while (fgets(rc, 100, fp) != NULL)
printf("%s", rc);
status = pclose(fp);
if (status == -1) {
printf("error:%d: %s", errno, strerror(errno));
} else { /* this means no error happened */
printf("success: pipe, closed.");
}
return 0;
}
请注意 main()
应返回 int
, 以及 Joachim Pileborg评论,fgets(...) == '\0'
错了,fgets()
返回 NULL
错误和NULL == '\0'
不一定是真的。
此外,pclose()
返回 -1
出错时,如果它不返回 -1
然后一切都按预期进行。
关于c - c程序的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28569142/