c - 在套接字 C 中发送字符串?

标签 c string bash sockets

我正在尝试发送这个字符串:

服务器代码:

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: array must be initialized with a brace-enclosed initializer

是否可以通过这种方式将grep结果发送给客户端?

最佳答案

system(3) 返回 fork(2) 的状态,但不是 fork 程序的标准输出。标准解决方案是使用管道:

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

关于c - 在套接字 C 中发送字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4283235/

相关文章:

c - 在 C 中使用函数初始化数组变量

javascript - 按空格拆分字符串但不在括号内

linux - 如何复制或删除 bash 中的特定行并将它们创建到新文件中

linux - Shell脚本从5个不同的目录获取数据

Git: merge stash 了某些更改

c - GDB 说 "no symbol table,"但 nm 显示文件有调试符号

c - 通过引用和扫描值传递矩阵

我们可以使用单个 malloc() block 来表示两种不同的类型吗?

c++ - std::cout 在 QNX 中不打印\n 之后的字母

sql - 使用 PIVOT 函数 (Oracle) 的行到列