Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 多线程应用程序中的printf笑话?_C_Pthreads_Printf - Fatal编程技术网

C 多线程应用程序中的printf笑话?

C 多线程应用程序中的printf笑话?,c,pthreads,printf,C,Pthreads,Printf,下面的代码是如何生成的 while(1) { client_name_len = sizeof(struct sockaddr_in); newsockfd = accept(sockfd, (struct sockaddr *)&client_name, &client_name_len); if (newsockfd < 0) { perror("ERROR on accept"); printf("Finished\n"); clo

下面的代码是如何生成的

while(1) {
  client_name_len = sizeof(struct sockaddr_in);
  newsockfd = accept(sockfd, (struct sockaddr *)&client_name, &client_name_len);
  if (newsockfd < 0) {
    perror("ERROR on accept");
    printf("Finished\n");
    close(sockfd);
    exit (EXIT_FAILURE);
  }
  printf("a:");
  pthread_t thread1;
  int *addr = (int*)malloc(sizeof(int));
  *addr = newsockfd;
  pthread_create( &thread1, NULL, &ProcessClient, (void*)addr);
}
问题是
perror(“接受时出错”)
printf(“完成的\n”)
printf(“a:”)
在同一个线程中执行,但输出是混合的

ProcessClient不输出任何内容,也不创建任何线程。
sockfd
是一个标准的侦听tcp套接字。

printf(“a:”)
printf(“已完成”)缓冲I/O将被发送到标准输出

perror(“接受时出错”)未缓冲(或立即刷新)I/O将进入stderr

因此,在accept上的
错误之后显示的许多
a:
:太多打开的文件实际上是
printf()

有关解决此问题的详细信息和方法,请参阅。

the
printf(“a:”)
printf(“已完成”)缓冲I/O将被发送到标准输出

perror(“接受时出错”)未缓冲(或立即刷新)I/O将进入stderr

因此,在accept上的
错误之后显示的许多
a:
:太多打开的文件实际上是
printf()


有关解决此问题的详细信息和方法,请参阅。

正如Michael指出的,第一个问题是您使用的是两个不同的流(stdout和stderr),其中一个是缓冲流,而另一个是非缓冲流。但是,您也将输出分解为多个stdio调用,这使其成为非原子的。我建议将
替换为:

printf("ERROR on accept: %s\n", strerror_l(errno));
或者将其他
printf
调用切换为在
stderr
上使用
fprintf
,以便在写入哪个流时保持一致


然后,为了使其原子化,在函数开始时调用
flockfile(f)
,在返回之前调用
funlockfile(f)
(其中
f
被您选择使用的
stdout
stderr
中的任何一个替换)。或者,如果您真的想同时使用这两个数据流,您可以同时锁定这两个数据流…

正如Michael指出的,第一个问题是您使用的是两个不同的数据流(stdout和stderr),其中一个是缓冲的,而另一个是非缓冲的。但是,您也将输出分解为多个stdio调用,这使其成为非原子的。我建议将
替换为:

printf("ERROR on accept: %s\n", strerror_l(errno));
或者将其他
printf
调用切换为在
stderr
上使用
fprintf
,以便在写入哪个流时保持一致


然后,为了使其原子化,在函数开始时调用
flockfile(f)
,在返回之前调用
funlockfile(f)
(其中
f
被您选择使用的
stdout
stderr
中的任何一个替换)。或者,如果您真的还想同时使用这两个,您可以同时锁定这两个…

有什么好笑的?要么是丰齐写的,要么是加拿大人写的。:-)我猜OP的意思是“窒息”。但“笑话”的问题更有趣。笑话是什么?要么是丰齐写的,要么是加拿大人写的。:-)我猜OP的意思是“窒息”。但“笑话”的问题更有趣。