Reputation: 75
In college I am learning communication between processes, and I have this exercise where I have to get a parent process link to a child through a pipe, the child runs the cmd sort fx.txt
and sends to the parent the output, which the parent should print.
The content of fx.txt
is
b
a
After some search, found out popen()
would be a good choice, and following some example code this is what I wrote:
#include <stdio.h>
#include <unistd.h>
#define SIZE 255
int main() {
FILE *file;
char *cmd = "sort fx.txt";
file = popen(cmd, "r");
if (file == NULL) {
printf("error opening pipe\n");
return 1;
}
char *str;
//print sorted lines
while (fgets(str, SIZE, file) != NULL) {
printf("%s", str); // \n already stored in str
}
pclose(file);
return 0;
}
I get segmentation fault on the line of fgets()
.
After that, I randomly tried to fix it by creating another pointer and assigning the return of fgets()
to it.
The change is as follows:
char *str;
char *s;
//print sorted lines
while ((s = fgets(str, SIZE, file)) != NULL) {
printf("%s", str); // \n already stored in str
}
It worked and the output is:
a
b
I would be thankful if someone could explain me this behaviour.
Upvotes: 1
Views: 297
Reputation: 224944
char *str;
Is an uninitialized pointer. When you call fgets
with it as an argument, you cause undefined behaviour. Allocate some actual space and use that:
char str[MAX_LINE_LENGTH];
Where MAX_LINE_LENGTH
is something reasonable for your program.
Upvotes: 1