我有以下代码作为接受传入套接字连接的服务器的主循环。
目前宏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 实现。如何修复段错误错误?
最佳答案
pthread_create(&thread_id, NULL, attendFTP(socketfd, hit), NULL);
此代码将调用结果传递给具有给定参数的 attendFTP()
- 并且此结果始终为 NULL。
因此 pthread_create 尝试在 NULL 地址启动函数,相应地失败了。
如果您使用 -pedantic
参数运行编译器,编译器会告诉您所做的事情是错误的。如果没有 -pedantic
,gcc 允许一些“扩展”,这可能会隐藏错误。顺便说一句,这就是为什么在我看来 -pedantic
是必须的。
您真正想要的是将一些参数传递给您的线程函数。不幸的是,它在 C pthread 中确实很复杂,并且需要您分配和释放所述结构。像这样的事情:
struct args {
int fd;
int hit;
};
...
pthread_t thread_id;
struct args* args = malloc(sizeof(struct args));
args->fd = socketfd;
args->hit = hit;
if(pthread_create(&thread_id, NULL, attendFTP, args))
....
void* attendFTP(void* vargs)
{
struct args* args = vargs;
ftp(args->fd, args->hit);
free(args);
return NULL;
}
关于c - 接受系统调用时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36342876/