我在远程 shell 中使用命令时遇到问题。每次我使用 ls 或 pwd 等命令或其他命令时,我都必须按 Enter 或其他命令才能向客户端显示结果。我认为它与缓冲或文件描述符有关,但我尝试了任何方法,但无法让它正常工作。在服务器端,结果立即可见。感觉我的客户陷入了上一个“回合”。
这就是我的服务器在找到连接时所做的事情。
pid_t pid, wpid;
int status;
pid = fork();
if (pid > 0) {
/* Thats the Parent */
longjmp(bufferB,1);
} else if (pid == 0) {
/* Thats the Child */
dup2(cli_sock, STDOUT_FILENO);
while (1) {
/* prepare buffer */
memset(buf, 0, BUF_SIZE);
/* get request */
ret = read(cli_sock, buf, BUF_SIZE - 1); /* -1: '\0' ending */
if (ret < 0)
term("Couldn't read from socket");
/* handle no input, e.g. client exit during open connection */
if (ret == 0)
break;
/* handle request */
lsh_loop(buf);
if (!strcmp("exit", buf))
break;
if (ret < 0)
term("Couldn't write to socket");
}
fprintf(stderr, "A Connection was closed!\n");
}
/* clean up */
term(NULL);
return EXIT_SUCCESS;}
这就是我的客户端在连接后所做的事情。
while (1) {
/* get user command */
ret = getline(&cmd, &cmd_sz, stdin);
if (ret < 0)
term("Couldn't get command from user");
buf[ret] = '\0';
/* send command request to server */
ret = write(sock, buf, ret);
if (ret < 0)
term("Couldn't write to socket");
/* exit if required */
if (!strcmp("exit\n", buf))
break;
/* get server response */
memset(buf, 0, BUF_SIZE);
ret = recv(sock, buf, BUF_SIZE - 1, MSG_EOR); /* -1 for '\0' ending */
if (ret < 0)
term("Couldn't read from socket");
/* output response */
printf("%s", buf);
fflush(stdout);
}
term(NULL);
return EXIT_SUCCESS;}
这是来自 shell 的一个小示例。
void lsh_loop(char *line) {
char prompt_puffer[200];
char **args;
int status;
setjmp(bufferA);
if (getcwd(prompt_puffer, sizeof(prompt_puffer)) == NULL) {
fprintf(stderr, "lsh: no directory found");
exit(EXIT_FAILURE);
}
strcat(prompt_puffer, "$ ");
args = lsh_split_line(line);
status = lsh_execute(args);
/* Using a status variable returned by lsh_execute() to determine when to exit */
fprintf(stderr, "%s\n", prompt_puffer);
printf("%s", prompt_puffer);
fflush(stdout);}
感谢您的宝贵时间。
最佳答案
您要让它先从命令行获取输入,然后才能使用 ret = getline(&cmd, &cmd_sz, stdin);
从端口接收信息。如果您想读取端口数据,则可以更改客户端的顺序,然后然后接受命令行输入,或者更好:为客户端提供一个不断读取、打印和循环的“读取线程”。
关于c - 从套接字读取()每次都需要额外的输入(C编程远程shell),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30582471/