2014-03-04 52 views
0

當我運行代碼,它似乎並沒有跑整個主功能時,這條線爲什麼accept()(用於套接字連接)會導致我的代碼被阻塞?

connect_sock = accept(sock, (struct sockaddr *)&serv_name, &len); 

是它。它甚至不會在開始時打印第一個cout,但是當我評論它時它工作正常,有人可以告訴我這個的原因嗎?

#include <sys/types.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <signal.h> 
#include <sys/socket.h> 
#include <sys/un.h> 
#include <netinet/in.h> 
#include <iostream> 

#define PORT 1227 
#define SIM_LENGTH 10; 
using namespace std; 
void clean_up(int cond, int *sock){ 
cout<<"exiting"; 
close(*sock); 
exit(cond); 
} 

int main(void){ 
cout<<"working; 
int sock; 
int connect_sock; 
struct sockaddr_in serv_name; 
size_t len; 
int count; 

sock = socket(AF_INET, SOCK_STREAM, 0); 
if(sock<0){ 
cout<<"Error connecting to socket"; 
clean_up(1, &sock); 
} 
bzero(&serv_name, sizeof(serv_name)); // set name as physical address 
serv_name.sin_family = AF_INET; 
serv_name.sin_port = htons(PORT); 
if(bind(sock,(struct sockaddr *)&serv_name, sizeof(serv_name))<0){ 
cout<<"error naming channel"; 
clean_up(1, &sock); 
} 
cout<<"waiting for connection from client"; 
listen(sock, 1); 
len = sizeof(serv_name); 
connect_sock = accept(sock, (struct sockaddr *)&serv_name, &len); 
cout<<connect_sock; 
cout<<"server wrote"; 
close(connect_sock); 
cout<<"connect?"; 
} 
+0

您的代碼不會「失敗」。它在accept()中被阻塞。 – EJP

+0

你能否澄清它阻止了什麼? –

回答

1

它正在等待連接。它不打印第一個cout,因爲你沒有要求。嘗試:

cout<<"waiting for connection from client"<<endl; 
+0

我試圖連接客戶端,但它仍然顯示沒有輸出 –

+0

你能說明爲什麼我必須添加endl嗎? –

+1

該程序只做你要求它做的事情。如果你想要輸出到終端,你必須這樣做。 –

相關問題