【发布时间】:2021-11-07 05:51:21
【问题描述】:
我一直在做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
【问题讨论】:
-
这个程序中没有执行ls或其他任何东西的东西;程序在 5 秒后退出,然后您的 shell 可能会执行您在程序运行时输入的附加文本行。你可以通过运行“sleep 5”而不是这个程序来获得相同的行为,或者运行任何不会立即返回的 shell 命令或从标准输入读取任何输入。