c - 具有重定向输出应用程序的 Linux C TCP 套接字客户端/服务器

标签 c linux redirect tcp

首先让我说这是操作系统类(class)的家庭作业,我不是程序员,尤其不是 C 语言的程序员。我已经做了一个星期了,我只是被卡住了,我需要帮助。我必须创建 TCP 客户端和服务器应用程序,其中将 linux 命令键入客户端,在服务器上执行,并将输出重定向回客户端。我理解这个概念,并且 90% 以上的工作正常。 “ls”、“ls -lpq”、“cat somefile”、“man somecommand”等命令都可以正常工作。我遇到麻烦的地方是不返回任何信息的命令,如“mkdir newdir”(如果目录已经存在,它可以正常工作,因为我得到了响应)。这对我来说是全新的,但在我看来,我的问题是服务器 recv 命令阻塞,因为没有要接收的信息。我不知道如何解决这个问题,我已经处理这个问题一个星期了。我的时间不多了,我还必须实现文件上传和下载,我不知道从哪里开始,但在我解决这个问题之前我什至无法开始处理它。

谢谢

    // this is where I think the problem is
    while ((rcvd_bytes = recv(sock_fd, recv_str, sizeof(recv_str), 0)) > 0 ) {
        // Zero out the inputCopy buffer
        memset(&inputCopy, 0, sizeof(inputCopy)+1);

        // Copy the recv_str into a new string so that
        // we can work with it.
        strcpy(inputCopy, recv_str);

        argcount = parsecommand(inputCopy, args);

        //Send the message back to client
        dup2(sock_fd, 1);

        if((status = forkAndExecute(args)) != 0) {
            //printf("Command %s returned %d.\n", args[0], status);
        }

            // as a test is I uncomment the following line mkdir newdir
            // returns but the following commands are messed up - as I expect.
        //printf("\n");

        memset(&recv_str, 0, sizeof(recv_str)+1);
        fflush(stdout);
    }  

    if(rcvd_bytes == 0) {
    puts("Client disconnected");
    fflush(stdout);
    }
    else if(rcvd_bytes == -1) {
    perror("recv failed");
    exit(0);
    }

最佳答案

听起来你需要使用 select .

if(select(fdmax+1, &my_fdset, 0, 0, NULL) > 0) // there is data available to be read
    recv(...)

其中 fdmax 是最大的文件描述符(select 想要 +1),my_fdset 是一个文件描述符集,您可以使用 FD_SET( sockfd, &my_fdset);.

这只会在有可用数据时接收。希望对您有所帮助。

编辑:

当我编写一个简单的客户端/服务器程序通过 TCP 套接字发送/接收字符串时,我问了一个类似的问题。我在该线程上发布了最终使用的代码 here .我的不同之处在于我想要一个程序来发送和接收,但如果你看看我的发送器或接收器函数,你可能能够调整一些东西让你的程序做你想做的事。

关于c - 具有重定向输出应用程序的 Linux C TCP 套接字客户端/服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15562150/

相关文章:

mysql - 升级到 5.6 后找不到 mysql/mysql.h

c - 返回类型为二维数组

python - SWIG 如何包装缓冲区(字符数组)和从 C 到 Python 的指针?

c - 子进程执行某些系统命令的结果无法通过管道发送到父进程

与 C ~ 运算符(按位非)混淆并比较 char 变量

linux - VM 上的 Docker Elasticsearch

linux - PERL sh : script_init: command not found

linux - tshark:特定传出端口的 http 事务信息

jsf - 如何在 JSF 中将对象从一个页面传递到另一个页面而不编写转换器

symfony - 如何在 Symfony2 重定向到登录页面之前获取先前的 url