|
Win2k+Cygwinの環境です。
Cプログラミングの学習を始めました。
以下の様なリストtest.cを試してみました。
処理状況を見るために途中、
printf("処理A地点");とprintf("処理A地点");を挿入しています。
ところが
$ gcc -o test test.c
$ ./test.exe
Input port number:50000
successfully bound, now waiting.
で止まってしまい、
「処理A地点」が表示されません。
どうして、表示されないのでしょうか?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <curses.h>
#include <signal.h>
#include <unistd.h>
#define BUF_LEN 20
static int width;
static fd_set mask;
static char buf[BUF_LEN]; /* 送受信兼用バッファ */
static int session_soc; /* socket */
int setup_server(in_port_t port){
struct sockaddr_in me; /* 自分のソケットのアドレス */
int soc_waiting; /* 接続待ちのソケット */
int soc; /* 通信に使うソケット */
/* 自分のアドレスを sockaddr_in 構造体に設定 */
memset((char *)&me, 0, sizeof(me));
me.sin_family = AF_INET;
me.sin_addr.s_addr = htonl(INADDR_ANY);
me.sin_port = htons(port);
/* IPv4 でストリーム型のソケットの作成 */
if ((soc_waiting = socket(AF_INET,SOCK_STREAM,0)) < 0 ){
perror("socket");
return -1;
}
/* ソケットに自分のアドレスを設定 */
if (bind(soc_waiting,(struct sockaddr *)&me,sizeof(me)) == -1){
perror("bind");
return -1;
}
/* ソケットで接続待ちの設定 */
listen(soc_waiting,1);
fprintf(stderr,"successfully bound, now waiting.\n");
printf("処理A地点");
/* 接続要求があるまでブロック */
soc = accept(soc_waiting, NULL, NULL);
printf("処理B地点");
/* 接続待ちに使ったソケットを閉じる */
close(soc_waiting);
/* 通信に使うソケットのディスクリプタを返す */
return soc;
}
int main(void){
int soc; /* ソケットのディスクリプタ */
char port0[12];
in_port_t port;
printf("Input port number:");
fgets(port0,sizeof(port0),stdin);
port=atoi(port0);
printf("port=%u",port); // in_port_t型はunit16_t型
/* 接続受付まで */
if( (soc = setup_server(port) ) == -1)exit(1);
return 0;
}
|