2010-02-09 6 views
-1

전 C에서 프로그램을 쓰고 있어요 그리고 난 나에게 감사는 COM 포트

+4

COM 포트를 사용하는 것은 OS마다 다르므로 원하는 OS를 알려줘야합니다. –

+2

OS 특정 * 및 * 환경 특정. 표준 C 라이브러리 만? 프레임 워크가 전혀 없습니까? –

+0

임베디드 시스템 용으로 개발 중이지만 사용할 운영 체제는 언급하지 않았다는 내용에 유의하십시오. 리눅스? Windows? BSD? 아마도, 다른 것? –

답변

1

나는 당신이 무엇인지 잘 모르겠어요 도와주세요 내가 COM 포트 에서 수신 할 수있는 방법을 알고 있으며 에서 데이터를 읽고 싶어을에 들어 찾고, 그러나 이것은 유닉스에 도움이 자사의 수 : Linux의

#include <stdio.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <bstring.h>   /* bzero(), bcopy() */ 
#include <unistd.h>   /* read(), write(), close() */ 
#include <errno.h> 
#include <sys/signal.h> 

int obtain_socket(int port); 
void show_message(int sd); 
void close_down(int sigtype); 


#define PORT 2001   /* default port for server */ 
#define SIZE 512   /* max length of character string */ 

int ssockfd;  /* socket for PORT; global for close_down() */ 

int main() 
{ 
    int sd, client_len; 
    struct sockaddr_in client; 

    signal(SIGINT, close_down); /* use close_down() to terminate */ 

    printf("Listen starting on port %d\n", PORT); 
    ssockfd = obtain_socket(PORT); 
    while(1) { 
    client_len = sizeof(client); 
    if ((sd = accept(ssockfd, (struct sockaddr *) &client, 
         &client_len)) < 0) { 
     perror("accept connection failure"); 
     exit(4); 
    } 
    show_message(sd); 
    close(sd); 
    } 
    return 0; 
} 


int obtain_socket(int port) 
/* Perform the first four steps of creating a server: 
    create a socket, initialise the address data structure, 
    bind the address to the socket, and wait for connections. 
*/ 
{ 
    int sockfd; 
    struct sockaddr_in serv_addr; 

    /* open a TCP socket */ 
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { 
    perror("could not create a socket"); 
    exit(1); 
    } 

    /* initialise socket address */ 
    bzero((char *)&serv_addr, sizeof(serv_addr)); 
    serv_addr.sin_family = AF_INET; 
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); 
    serv_addr.sin_port = htons(port); 

    /* bind socket to address */ 
    if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { 
    perror("could not bind socket to address"); 
    exit(2); 
    } 

    /* set socket to listen for incoming connections */ 
    /* allow a queue of 5 */ 
    if (listen(sockfd, 5) == -1) { 
    perror("listen error"); 
    exit(3); 
    } 
    return sockfd; 
} 


void show_message(int sd) 
/* Print the incoming text to stdout */ 
{ 
    char buf[SIZE]; 
    int no; 

    while ((no = read(sd, buf, SIZE)) > 0) 
    write(1, buf, no); /* write to stdout */ 
} 


void close_down(int sigtype) 
/* Close socket connection to PORT when ctrl-C is typed */ 
{ 
    close(ssockfd); 
    printf("Listen terminated\n"); 
    exit(0); 
} 
+0

안녕하세요, 임베디드 시스템에서이 프로그램을 실행하고 싶습니다. – Mehdi

+0

시스템에 어떤 컴파일러를 사용하고 있습니까? 모든 경우에이 프로그램을 컴파일하고 얻는 것을보십시오. – Vivek

+0

감사합니다. Vivek. Linux에서 컴파일하려면 다음을 수행하십시오. 으로 변경하십시오. "include "을 추가하십시오. –

관련 문제