【问题标题】:how to send unix command from client to server then return the result?如何将 unix 命令从客户端发送到服务器然后返回结果?
【发布时间】:2011-09-30 06:58:52
【问题描述】:

我正在尝试从客户端向服务器发送 unix 命令,等待服务器执行然后将结果返回给客户端。

我设法使连接正常工作,但我不知道如何继续。这就是我应该走的方向吗?

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

#define MAXLINE 1024

int main(void)
{
  int pfd[2], n
  pid_t pid;

  char buf[MAXLINE]
  char test[] = "pipe test\n";

  if (pipe(pfd) < 0)
    perror("pipe error");

  if ((pid = fork()) < 0)
    perror("fork error");
  else
    if (pid == 0)
    {
      close(pfd[1]);
      n = read(pfd[0], buf, MAXLINE);
      printf("read %d byte: \n", n);
      fflush(stdout);
      write(1, buf, n);
    }
    else
    {
      close(pfd[0]);
      write(pfd[1], test, sizeof(test));
    }
  exit(0);
}

感谢您的帮助,ty 班多

【问题讨论】:

  • 只有当客户端和服务器在同一个盒子里时,你才能使用管道。否则它将是 TCP/IP。参考文献man 7 ip, man 7 tcp.

标签: c client-server fork pipe divide-and-conquer


【解决方案1】:

您想要popen(3),但请注意基于不受信任的用户输入在服务器上运行命令的安全隐患 - 这是一个很大的禁忌。

【讨论】:

  • 我必须把它作为一个学校项目来做,所以它值得信赖
猜你喜欢
  • 1970-01-01
  • 2021-08-01
  • 2019-01-27
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
相关资源
最近更新 更多