gpt4 book ai didi

c - 为什么使用 AF_UNIX 系列的文件描述符会导致 accept() 出现 "invalid argument"错误?

转载 作者:太空宇宙 更新时间:2023-11-04 04:31:21 25 4
gpt4 key购买 nike

这给我一个无效的参数错误:

int listenfd = socket(AF_UNIX, SOCK_STREAM, 0);
*clientfdp = accept(listenfd, (SA *) &clientAddr, &clientLen);

虽然这不是

int listenfd = socket(AF_INET, SOCK_STREAM, 0);
*clientfdp = accept(listenfd, (SA *) &clientAddr, &clientLen);

但我需要它是 AF_UNIX。这是怎么回事?我也检查了所有地方的错误。 socket() 的输出在任何一种情况下都很好,它只是在 accept 期间。

完整代码如下:

// forward declarations
int error_msg( char * msg );
int usage( char name[] );

// a function to be executed by each thread
void * recv_log_msgs( void * arg );

// globals
FILE * log_fd; // opened by main() but accessible by each thread
typedef struct sockaddr SA;

int error_msg( char * msg )
{
printf( "%s\n", msg );
return -1;
}

void * recv_log_msgs( void * arg ) //Thread Routine
{
// loops to receive messages from a client;
// when the connection is closed by the client,
// close the socket
int clientfd = *((int *)arg);
char buffer[1500];
memset(buffer, 0, 1500);
int currentPos = 0;
int bytesRec;
int recvng = 1;

while(recvng){
bytesRec = recv(clientfd, buffer, 1500-currentPos, 0);
currentPos += bytesRec;
if(buffer[currentPos - 1] == '\n')
recvng = 0;
}

fprintf(log_fd, "LOGGER %d %s", clientfd, buffer);
close(clientfd);
return NULL;
}

int usage( char name[] )
{
printf( "Usage:\n" );
printf( "\t%s <log-file-name> <UDS path>\n", name );
return 1;
}

int main( int argc, char * argv[] )
{
if ( argc != 3 )
return usage( argv[0] );

log_fd = fopen(argv[1], "a");

// create a server socket
// domain (i.e., family) is AF_UNIX
// type is SOCK_STREAM

socklen_t clientLength = sizeof(struct sockaddr_un);
struct sockaddr_un clientAddr;
clientAddr.sun_family = AF_UNIX;
strcpy(clientAddr.sun_path, argv[2]);

pthread_t tid;

int listenfd = socket(AF_UNIX, SOCK_STREAM, 0);

// unlink the UDS path)
unlink(argv[2]);

// bind the server socket
bind(listenfd, (SA *)&clientAddr, clientLength);

// listen
listen(listenfd, 1024);
// loop to wait for connections;
// as each connection is accepted,
// launch a new thread that calls
// recv_log_msgs(), which receives
// messages and writes them to the log file
while(1){
printf( "Waiting for a connection on UDS path %s...\n", argv[2] );
int * clientfdp = malloc(sizeof(int));
*clientfdp = accept(listenfd, (SA *) &clientAddr, &clientLength);
pthread_create(&tid, NULL, recv_log_msgs, clientfdp);
printf("%d",errno);
return 0;
}

// when the loop ends, close the listening socket
close(listenfd);

// close the log file
fclose(log_fd);

return 0;
}

最佳答案

main() 函数在调用 pthread_create() 后无法调用 pthread_join()

结果是进程在线程有机会向日志文件写入任何内容之前退出。

关于c - 为什么使用 AF_UNIX 系列的文件描述符会导致 accept() 出现 "invalid argument"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35916363/

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