【发布时间】:2016-07-20 11:11:15
【问题描述】:
我将以下代码用作接受传入套接字连接的服务器的主循环。
此时宏 OperationMode 被定义为 1,因此它将执行 pthread 逻辑。
for (hit = 1 ;; hit++) {
printf("Got here\n\n");
length = sizeof(cli_addr);
/* block waiting for clients */
socketfd = accept(listenfd, (struct sockaddr *) &cli_addr, &length);
if (socketfd < 0)
printf("ERROR system call - accept error\n");
else
{
printf("Testing\n\n\n");
#ifdef OperationMode
pthread_t thread_id;
if(pthread_create(&thread_id, NULL, attendFTP(socketfd, hit), NULL))
{
perror("could not create thread");
return 1;
}
#else
pid = fork();
if(pid==0)
{
ftp(socketfd, hit);
}
else
{
close(socketfd);
kill(pid, SIGCHLD);
}
#endif
}
}
我能够为第一个传入的套接字连接创建一个线程,但是一旦我遍历循环,我就会在该行中遇到分段错误错误
socketfd = accept(listened, (struct sockaddr *) &cli_addr, &length);
我的attendFTP函数有以下代码
void *attendFTP(int fd, int hit)
{
ftp(fd, hit);
return NULL;
}
这非常适合 fork 实现。如何修复分段错误错误?
【问题讨论】:
-
除非
attendFTP()是一个返回指向函数的指针的函数,否则您将错误地使用pthread_create()。 -
@EOF 我已经添加了我的
attendFTP()函数。但我相信我使用正确 -
您没有正确使用它。原型是
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);。如果您希望线程执行的函数需要多个参数,您可能需要传递一个指向struct的指针。
标签: c sockets pthreads posix ansi