2015-03-31 57 views
1

例如,假设我有一个文件server.c,它不打印任何东西,但是有一个字符串,例如:“鱼在空中游泳”。我想要做的是让child.c打印server.c的字符串 甚至可能吗?我被告知使用管道(如popen())会有所帮助。但我找不到我想要的东西。如何从另一个c文件输入输出?

+2

我想你的意思是“我怎样才能把另一个程序的输出作为我的输入?”如果不是,那么我不明白你在问什么 – 2015-03-31 01:18:02

+0

目前还不清楚你要求什么,但是如果你试图将输出从一个程序输入到另一个程序,为什么不使用[pipe](http: //en.wikipedia.org/wiki/Pipeline_%28Unix%29),就像在命令行上管道数据时一样,例如'ls -la | more'。 – 2015-03-31 01:29:22

+0

@AjjandroDiaz是的,这就是我的意思!啊哈,对不起,我的大脑由于阅读了许多关于C. – 2015-03-31 11:07:03

回答

2

我敢肯定有可能使用管道功能(检查像这个网站unixwiz.net/techtips/remap-pip-fds.html这样的东西),但你描述的声音像另一个客户端连接到服务器并通过套接字将字符串发送给它。使用套接字还会打开通过网络检查服务器字符串的功能。通常,在服务器进行错误/额外日志检查时,服务器可以通过打开日志文件或通过套接字发送日志文件来处理。如果安全问题存在,您可以决定将其发送给通过TLS连接使用PSK的特定客户端。

对于TLS例子检查出https://github.com/wolfSSL/wolfssl-examples

添加在代码用于输送

receiver.c

1 #include <stdio.h> 
    2 #include <stdlib.h> 
    3 #include <unistd.h> 
    4 
    5 int main() { 
    6 
    7  char buffer[1024]; 
    8 
    9  fscanf(stdin, "%s", buffer); 
10 
11  printf("receiver got data and is printing it\n"); 
12  printf("%s\n", buffer); 
13 
14  return 0; 
15 } 

sender.c

1 #include <stdio.h> 
    2 #include <stdlib.h> 
    3 #include <unistd.h> 
    4 
    5 
    6 int main() 
    7 { 
    8  FILE *output; 
    9 
10  output = popen ("./receiver","w"); 
11  if (!output) { 
12   /* error checking opening pipe */ 
13   fprintf(stderr, "could not open pipe\n"); 
14   return 1; 
15  } 
16 
17  fprintf(output, "%s", "hello_world\n"); 
18 
19  if (pclose (output) != 0) { 
20   /* error checking on closing pipe */ 
21   fprintf(stderr, " could not run receiver\n"); 
22   return 1; 
23  } 
24 
25  return 0; 
26 } 

编译和在同一目录中运行使用

gcc sender.c -o sender 
gcc receiver.c -o receiver 
./sender 
+0

哇,这听起来很复杂。但是你是对的,客户端将连接到服务器以从服务器获取字符串并将其打印出来。我想知道是否可以使用流水线而不是通过TLS连接来完成这项工作? 如果我确实想通过TLS连接进行操作,那么您是否有任何建议的参考?谢谢! – 2015-03-31 11:11:14

+0

嗨终极TC,编辑答案,希望它有帮助。我仍然建议使用TLS(如果担心安全性),或者至少使用纯TCP连接并通过套接字发送字符串。 – Sweetness 2015-03-31 21:20:57

+0

如果担心安全问题,首先要摆脱的是receiver.c中第9行的缓冲区溢出漏洞。 – 5gon12eder 2015-03-31 21:23:29