3

私がしようとしているのは、リモートサーバーに接続し、ローカルマシン上のファイルからコンテンツを読み取り、それをサーバーに送信することです。次に、サーバーの応答を取得して保存します。GET コマンドをテキスト ファイルに入れて、同じ結果を取得しようとしています。コードの一部を次に示します。ソケットとCを使用してこれを行っています。

if ( inet_pton(AF_INET,ip, &(nc_args->destaddr.sin_addr.s_addr)) <= 0 )
    printf("\n\t\t inet_pton error");


if (connect(sockfd, (struct sockaddr *) &nc_args->destaddr, sizeof(&nc_args->destaddr)) < 0)
{
    printf("\n\t\t Connection error");
    exit(1);
}
puts("\n\t\t Connection successful to ...");

// file parameter is taken from command line and passéd to this function

fp = fopen(file,"rb");
if ( fp == NULL)
{
    printf("\n\t\t File not found");
    exit(3);
}

else
{
    printf("\n\t\t Found file %s\n", file);

    fseek(fp, 0, SEEK_END);
    file_size = ftell(fp);
    rewind(fp);

    //allocate memory to the buffer dynamically

    buffer = (char*) malloc (sizeof(char)*file_size);
    if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);}
    for (i=0 ; i<sizeof(buffer); i++)
    {
        printf("\n\t\t %s", buffer);
    }
    printf("\n\t\t File contains %ld bytes!\n", file_size);
    printf("\n\t\t Sending the file now");
}


while (1)
{
    bytes_read = fread(buffer,1, file_size, fp);
     printf("\n\t\t The bytes read is %zd", bytes_read);
    if (bytes_read == 0) // We're done reading from the file
      {
          printf("\n\t\t The bytes read is %zd", bytes_read);
          break;
      }
    if (bytes_read < 0)
    {
        printf("\n\t\t ERROR reading from file");
    }

    void *p = buffer;

    while (bytes_read > 0)
    {
        ssize_t bytes_written = send(sockfd, buffer, bytes_read,0);
        if (bytes_written <= 0)
        {
           printf("\n\t\t ERROR writing to socket\n");
        }
        bytes_read -= bytes_written;
        p += bytes_written;
        printf("\n\t\t Bytes %zd written", bytes_written);
    }
}

printf("\n\n\t\t Sending complete.");

ここで起こっているのは、「接続に成功しました」というメッセージが表示され、「ファイルを送信しています」と表示され、プログラムが予期せず終了することです。$ をエコーする場合は? 終了コードとして 141 を取得します。サーバーから職場の別のサーバーに接続して結果を取得しようとしています。これら 2 つは正しく通信でき、問題なくコマンド ラインから GET コマンドを実行できます。コードからは機能していません。誰かが私に何が問題なのか教えてもらえますか?

4

2 に答える 2

8

Linux およびおそらく他の Unix では、戻りコードはプロセスが受信したシグナルをエンコードします。に対応するのは141 - 128そうです。13SIGPIPE

のエラー リターンをキャプチャするためにそのシグナルを発生させたくない場合は、いずれにせよsend、Linux では引数で toを使用MSG_NOSIGNALしてそのシグナルを禁止することができます。他のプラットフォームでは、その状況に対処するために、より複雑なシグナル ハンドラーをプログラムする必要がある場合があります。flagssend

于 2013-09-18T19:50:20.313 に答える