【发布时间】:2014-07-23 10:18:53
【问题描述】:
我正在 c 中使用 TCP 创建一个 FTP 服务器。我的文件传输出现问题,我希望能够从客户端向/从服务器“放置”或“获取”文件。 我正在使用 select() 处理多连接并使用线程来处理文件传输。 我创建了一个简单的 .c 示例来总结我的问题:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void *read_stdin(void * null)
{
int fd;
int len;
char ret;
char buff[1024];
fd = open("dest", O_RDWR | O_TRUNC | O_CREAT, 0600);
len = 1;
while (len)
{
ret = read(0, &len, 1);
len = atoi(ret);
if (len)
{
read(0, buff, len);
write(fd, buff, len);
}
}
return (null);
}
int main()
{
pthread_t t;
int fd;
char len;
char buff[1024];
pthread_create(&t, NULL, &read_stdin, NULL);
fd = open("source", O_RDONLY);
while ((len = read(fd, buff, 1024)))
{
write(0, &len, 1);
write(0, buff, len);
}
write(0, "0", 1);
pthread_join(t, NULL);
return (0);
}
现在我的问题是线程中的 read() 被阻塞了,它没有从主进程读取我在 STDIN 上写的内容,我不明白为什么,它在我的程序中做同样的事情吗但不是从标准输入读取,而是从套接字读取,但为了简单起见,我在此示例中使用了标准输入。
谢谢!
编辑:将 main 中的 len 从 int 更改为 char,并使用 char 读取我的 thread_func,然后使用 atoi() 进行转换。
【问题讨论】:
-
您是否将您的套接字设置为非阻塞——
fcntl(sockfd, F_SETFL, O_NONBLOCK);?你真的在使用read()从套接字读取吗? -
并行运行
read不会使其成为非阻塞的。您可能想在STDIN_FILENO上select阅读。 -
当我说它阻塞时,我的意思是它没有读取我在主进程中写的内容,我不希望它是非阻塞的,我希望它读取我的我在 STDIN 上写作
-
这段代码有很多问题:写入标准输入,
int/char到处不匹配,在char上调用atoi(),不检查返回值。 .
标签: c multithreading