gpt4 book ai didi

c - 阻塞 UDP 套接字 C

转载 作者:行者123 更新时间:2023-11-30 14:57:12 25 4
gpt4 key购买 nike

有人可以解释一下为什么在调用 ConnectionSocket() 函数之前没有执行这个 printf 吗?

我知道套接字默认情况下是阻塞的,所以它会等待直到收到一些东西。但此时的函数还没有执行,为什么不先在屏幕上打印“test”呢?

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <wiringPi.h>
#include <stdbool.h>
#include <sys/time.h>
/* Global variables */
unsigned char buffer[1];
struct sockaddr_in serverAddr, clientAddr;
struct timeval timeout={10,0}; //set timeout for 10 seconds
int udpSocket, slen = sizeof(clientAddr);


int main(){
printf("test"); // -> for the first time executed when receiving a byte
initialize_pins();
ConnectionSocket();
loop();

return 0;
}

void ConnectionSocket(){

/*Create UDP socket*/
udpSocket = socket(AF_INET, SOCK_DGRAM, 0);

/*Configure settings in address struct*/
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(7891);
serverAddr.sin_addr.s_addr = inet_addr("192.168.0.184");
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);

/* set receive UDP message timeout */
setsockopt(buffer,SOL_SOCKET,SO_RCVTIMEO,(char*)&timeout,sizeof(struct timeval));

bind(udpSocket, (struct sockaddr *)&serverAddr, sizeof(serverAddr));

}

最佳答案

printf() 将要写入的字符串存储在缓冲区中,如果缓冲区已满,或者插入了 '\n' 或者调用 fflush(),或者如果标准函数调用 fflush() 或到达程序末尾。

我用 write() 编写了一个直接在屏幕上打印的示例。

#include <stdio.h>
#include <unistd.h>

int main(void)
{
printf("1"); // stored in a buffer but not printed on screen
write(STDOUT_FILENO, "2", 1); // directly printed on screen (2)
printf("3"); // stored in a buffer but not printed on screen
write(STDOUT_FILENO, "4", 1); // directly printed on screen (4)
fflush(stdout); // flushing stdout, 1 and 3 are printed
write(STDOUT_FILENO, "5", 1); // directly printed on screen (5)
printf("6\n"); // stored in a buffer then the buffer is printed on the screen because of '\n' (6\n)
printf("7"); // stored in a buffer but not printed on screen

return (0); // end of the program, 7 is printed
}

输出为 241356\n7

关于c - 阻塞 UDP 套接字 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44077903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com