The Segmentation fault
message gets printed by your shell, not by your program, when this signal is generated, and not caught, by some program which tried to access memory outside what is allocated to it.
Now, as to why you're only getting the segfault in your output, I think there are two things happening here:
- when you invoke a shell command using
sh -c
, you're actually invoking the command in a new shell. The seg fault message is coming from that new shell, not the one you're working in, and when you combine stdout and stderr with 2>&1
then you're also getting the stderr for the new shell. Which contains the segfault message. If you just run the command directly in the shell you're already using (i.e. echo "pass" | sudo -S u3-tool -i /dev/sdc > /tmp/u3info 2>&1
), then the redirection should work like you expect.
It's very possible that the seg fault is happening before the output line is fully buffered and flushed to the file, see this stackoverflow question. To answer why the output line appears in your terminal window, but not when redirected to a file, I must honestly say that I don't know why that happens, but I can verify the same behaviour on my machine with a simple program:
#include <stdio.h>
void main (void)
{
char *p; /* uninitialised pointer */
printf("hello\n"); /* print a line */
p[7] = 'a'; /* seg fault! */
}
And here is what happens when I compile and test it:
enyquist$ gcc segfault.c -o segfault
enyquist$ ./segfault
hello
Segmentation fault
enyquist$ ./segfault > file
Segmentation fault
enyquist$ cat file
enyquist$
TO illustrate the problem, we can actually fix this code, to ensure that the full message is flushed and printed before doing anything else, like so:
#include <stdio.h>
void main (void)
{
char *p; /* uninitialised pointer */
printf("hello\n"); /* print a line */
fflush(stdout); /* flush stdout stream */
p[7] = 'a'; /* seg fault! */
}
And the output....
enyquist$ gcc segfault.c -o segfault
enyquist$ ./segfault
hello
Segmentation fault
enyquist$ ./segfault > file
Segmentation fault
enyquist$ cat file
hello
enyquist$
So, to summarise, if you modify your shell commands like I suggested then I think the redirection will behave like you expect, but nothing else is behaving like you expect because you're getting a seg fault somewhere, so you need to find out what's causing that!