套接字连接突然用代码141关闭

use*_*093 3 c sockets

我尝试做的是连接到远程服务器,从本地计算机上的文件中读取内容并将其发送到服务器.然后捕获服务器响应并保存.我把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.");
Run Code Online (Sandbox Code Playgroud)

这里发生的是我收到消息"连接成功",然后显示"立即发送文件",然后程序意外退出.如果我回音$?我得到141作为退出代码.我正在尝试从我的服务器连接到工作中的其他服务器并获得结果.这两个可以正确通信,我可以从命令行运行GET命令而不会出现问题.它只是没有从代码工作.有人能让我知道问题是什么吗?

Jen*_*edt 8

在Linux和其他Unix上,返回代码对进程收到的信号进行编码.这是141 - 128如此13对应SIGPIPE.

如果您不希望引发该信号,因为您捕获了错误返回send,无论如何,在Linux上您可以MSG_NOSIGNALflags参数中使用send来禁止该信号.在其他平台上,您可能需要编写更复杂的信号处理程序来处理这种情况.

  • @Magn3s1um shell 添加了 128,这样您就可以区分退出代码(通常是低数字)和致命信号(也是低数字)。否则“SIGHUP”导致的死亡看起来与“exit(1)”相同 (2认同)