#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
int main()
{
int sock, newsock;
struct sockaddr server_name = {AF_UNIX, "Fred"};
socklen_t len=sizeof(struct sockaddr)+5;
if( (sock=socket(AF_UNIX,SOCK_STREAM,0)) ==-1)
{
printf("error creating socket");
return -1;
}
if( bind(sock,&server_name,len) != 0 ) //binding
{
printf("socket bind error ");
return -1;
}
if(listen(sock,10)!=0) //set sock to listen
{
printf("error listening");
return -1;
}
printf("Waiting for connections....");
while(1)
{
newsock=accept(sock, (struct sockaddr*)NULL, NULL);
char temp[1000]="gggggg\n";
write(newsock,temp,strlen(temp));
write(newsock,temp,strlen(temp));
close(newsock);
sleep(1);
}
return 0;
}
&#34;等待连接......&#34;不会出现在我的屏幕上。问题是什么?我到处尝试打印功能。什么都没有出现......问题是什么?我没有看到我关闭stdout ..任何人都可以帮忙吗?谢谢。
答案 0 :(得分:1)
标准输出默认为行缓冲。你的程序输出没有新行的东西,然后进入循环。你需要添加一个这样的新行:
printf("Waiting for connections....\n");
出于类似的原因,错误消息应该输出到标准错误,因为它没有被缓冲。
fprintf(stderr, "error creating socket\n");
答案 1 :(得分:0)
首先,您应该添加&#39; \ n&#39;添加日志结束:&#34;等待连接.... \ n&#34;然后将日志缓冲,然后输出。
其次,你的程序是错误的,正确的程序是这样的:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
int main()
{
int sock, newsock;
struct sockaddr_un server_name;
socklen_t len= sizeof(server_name);
unlink("Fred");
if( (sock=socket(AF_UNIX,SOCK_STREAM,0)) ==-1)
{
printf("error creating socket\n");
return -1;
}
server_name.sun_family = AF_UNIX;
strcpy(server_name.sun_path, "Fred");
if( bind(sock,(struct sockaddr*)&server_name,len) != 0 ) //binding
{
printf("socket bind error \n");
return -1;
}
if(listen(sock,10)!=0) //set sock to listen
{
printf("error listening\n");
return -1;
}
printf("Waiting for connections....\n");
while(1)
{
newsock=accept(sock, (struct sockaddr*)NULL, NULL);
char temp[1000]="gggggg\n";
write(newsock,temp,strlen(temp));
write(newsock,temp,strlen(temp));
close(newsock);
sleep(1);
}
return 0;
}