sub*_*ngh 9 c network-programming
我收到与err_sys()此代码相关的错误:
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
int sockfd;
if ((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
err_sys("can't create socket");
close(sockfd);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我收到链接器错误:
/tmp/cciuUVhz.o: In function `main':
getsockopt.c:(.text+0x38): undefined reference to `err_sys'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
功能在哪里err_sys()定义?
Pat*_*rik 19
将其置于代码之上:
void err_sys(const char* x)
{
perror(x);
exit(1);
}
Run Code Online (Sandbox Code Playgroud)
perror在stdio.h中定义
err_sys在Richard Stevens的"UNIX网络编程:套接字网络API"一书中使用.据我所知,这并不常见.
编辑:修复代码错误
这是来自TCP/IP Illustrated吗?我记得看过这个,并在附录中提供了定义:
#include <errno.h>
#include <stdarg.h>
/*
* Print a message and return to caller.
* Caller specifies "errnoflag".
*/
static void
err_doit(int errnoflag, int error, const char *fmt, va_list ap)
{
char buf[MAXLINE];
vsnprintf(buf, MAXLINE, fmt, ap);
if (errnoflag)
snprintf(buf+strlen(buf), MAXLINE-strlen(buf), ": %s",
strerror(error));
strcat(buf, "\n");
fflush(stdout); /* in case stdout and stderr are the same */
fputs(buf, stderr);
fflush(NULL); /* flushes all stdio output streams */
}
/*
* Fatal error related to a system call.
* Print a message and terminate.
*/
void
err_sys(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
err_doit(1, errno, fmt, ap);
va_end(ap);
exit(1);
}
Run Code Online (Sandbox Code Playgroud)