首页 > 解决方案 > 选择系统调用

问题描述

我一直在做socket编程,下面是select系统调用。如果这个程序在 5 秒内没有得到输入,它将终止,否则它将在终端中执行命令。我不明白程序的哪个部分使给定的消息作为终端中的命令执行。例如,如果我们键入 ls 并输入它会在终端中执行 ls 命令,但我不明白代码的哪一部分负责执行该ls命令。这是代码。

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
    fd_set rfds;
    struct timeval tv;
    int retval;

    /* Watch stdin (fd 0) to see when it has input. */

    FD_ZERO(&rfds);
    FD_SET(0, &rfds);
    /* Wait up to five seconds. */

    tv.tv_sec = 5; //in seconds
    tv.tv_usec = 0; //in microseconds

    retval = select(1, &rfds, NULL, NULL, &tv);

    /* Don't rely on the value of tv now! */

    if (retval == -1) //select failed
        perror("select()");
    else if (retval) //user input
        printf("Data is available now.\n");
    /* FD_ISSET(0, &rfds) will be true. */
    else
        printf("No data within five seconds.\n");
    exit(EXIT_SUCCESS);
}//program exit

标签: csockets

解决方案


我不明白代码的哪一部分负责执行 ls 命令。

代码的任何部分都没有执行命令。

当输入可用时,该命令将立即退出。它不会读取输入。相反,您启动程序的命令 shell 将在程序退出后读取输入并处理输入 - 即 shell 将执行ls


推荐阅读