Reputation: 430
I got segmentation fault for the code here.
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.
Code:
#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;
}
null pointer I guess? i tried with solutions given , but not worked. Somehow silly mistake I guess
sorry , the shell command will b sudo dmidecode | grep UUID
Upvotes: 0
Views: 2202
Reputation: 53016
This is wrong
fp = popen("sudo lshw |", "grep UUID");
maybe you mean, read popen()
fp = popen("sudo lshw | grep UUID", "r");
the call failed, but even though you checked for fp == NULL
, you continued anyway causing undefined behavior, and leading to the segmentation fault, the fp == NULL
check needs to abort the program, like this
#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;
}
note that main()
shall return an int
, and as Joachim Pileborg commented, fgets(...) == '\0'
is wrong, fgets()
returns NULL
on error and NULL == '\0'
is not necessarily true.
Also, pclose()
returns -1
on error, if it does not return -1
then everything went as expected.
Upvotes: 4