You don't need to do that. Just initialize ch with 0.
That's not the same at all !
Except of course that you said you were doing this for performance. Obviously running the program twice is inefficient (and idiotic).
Also, your execl call is wrong. You're passing ">" and "string.txt" as if you're trying to cause a redirection that way, but I can't see how that would work. And besides, that's what the dup2 call is for!
christop is right that system() will handle this stuff for you, even opening the file and redirection since it calls the shell (so you could pass it something like "/bin/netstat -antp > string.txt"). However, this is clearly less efficient than doing it yourself since the way you're doing it avoids calling the shell.
Try this:
Code:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
void die(char *msg) {
fprintf(stderr, "%s error -> %s.\n", msg, strerror(errno));
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[]) {
pid_t pid = fork();
if(pid == -1)
die("FORK(-1)");
else if(pid == 0) { // child
int fd = open("string.txt", O_RDWR | O_CREAT, 0755);
if(fd == -1)
die("OPEN(-1)");
dup2(fd, STDOUT_FILENO);
execl("/bin/netstat", "netstat", "-antp", (char *)NULL);
die("EXECL");
}
// parent
int status;
wait(&status);
if(status != 0)
die("NETSTAT");
FILE *file = fopen("string.txt", "r");
if(file == NULL)
die("FOPEN[file](NULL)");
int ch = 0;
while(ch != EOF) {
ch = fgetc(file);
printf("%c", ch);
}
fclose(file);
return 0;
}