use*_*650 2 c sockets fork pthreads
我正在编写一个C程序,一旦它接受客户端连接就会分叉.一旦发生这种情况,我想生成两个线程,但我似乎无法使其工作.
pthread_t t1, t2;
void *r_loop();
void *w_loop();
.
.
.
sockfd = accept(r_sockfd, (struct sockaddr *) &address, &len);
if (sockfd < 0)
printf("Error accepting\n");
if (!fork())
{
int r_thread = pthread_create(&t1, NULL, r_loop, NULL);
int w_thread = pthread_create(&t2, NULL, w_loop, NULL);
pthread_join(r_thread, NULL);
pthread_join(w_thread, NULL);
exit(0);
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,函数r_loop和w_loop不会被执行.
问题可能是这样:pthread_create()成功alwasy返回零.您传递给pthread_join()一个不正确的值(即零而不是t1和t2)使它们立即返回.然后,以下exit()也会杀死新的起始线程