Reputation: 25
I am trying to send this string:
Server code:
char bash[256] = "grep 'usernama' data/*.txt | awk -F':' '{print $1}' | uniq";
char result[1000] = system(bash);
send(connected, result,strlen(result), 0);
fflush(stdout);
Error message:
error: array must be initialized with a brace-enclosed initializer
Issit possiible to send the grep result to the client in that way?
Upvotes: 1
Views: 259
Reputation: 6327
system(3) returns you status of fork(2), but not stdout of forked program. Standard solution is using pipes:
char bash_cmd[256] = "grep 'usernama' data/*.txt | awk -F':' '{print $1}' | uniq":
char buffer[1000];
FILE *pipe;
int len;
pipe = popen(bash_cmd, "r");
if (pipe == NULL) {
perror("pipe");
exit(1);
}
fgets(buffer, sizeof(buffer), pipe);
len = strlen(bash_cmd);
bash_cmd[len-1] = '\0';
pclose(pipe);
Upvotes: 2
Reputation: 53310
system
doesn't capture the output from the command it runs, so it isn't possible to do what you want that way.
If you look at the system man page you can see it returns int
, the exit status of the command you run.
In order to capture the output of a process, you need to:
3 would be slightly simpler than 2, but would introduce security and reliability problems that wouldn't be present in 1 or 2.
Upvotes: 1
Reputation: 399863
The easiest way to do this, if you're willing to call system()
and run a shell, is probably to redirect the output to a file, then open the file, read its contents, and send that.
This of course opens up a bunch of problems (mainly race conditions and error handling), but it can perhaps be a bit simpler than just diving in and learning about fork()
and exec()
.
Upvotes: 0