开发者

sending string in sockets C?

开发者 https://www.devze.com 2023-01-27 14:08 出处:网络
I am trying to send this string: Server code: char bash[256] = \"grep \'usernama\' data/*.txt | awk -F\':\' \'{print $1}\' | uniq\";

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 messa开发者_运维技巧ge:

error: array must be initialized with a brace-enclosed initializer

Issit possiible to send the grep result to the client in that way?


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);


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:

  1. Find a library that does it for you.
  2. Code up your own fork/exec with pipes implementation.
  3. Redirect the output to a temporary file, then read that in. (From @unwind)

3 would be slightly simpler than 2, but would introduce security and reliability problems that wouldn't be present in 1 or 2.


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().

0

精彩评论

暂无评论...
验证码 换一张
取 消