首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SIGPIPE中的清理

SIGPIPE中的清理
EN

Stack Overflow用户
提问于 2010-12-04 12:46:28
回答 2查看 2.1K关注 0票数 1

我有一个在多个线程中共享的套接字连接池,一个死连接应该从池中删除,问题是我不知道SIGPIPE sighandler中哪个是死连接,在这种情况下有什么建议吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-12-04 12:51:50

解决这个问题的一种方法是忽略SIGPIPE。这意味着您的写操作(writesendmsg等)将返回一个错误,只要注意错误返回,就会知道哪个文件描述符失败了--因为一切都是同步的。

票数 5
EN

Stack Overflow用户

发布于 2013-07-19 17:03:10

以下程序与套接字无关,而是使用命名管道。我只是把程序放在这里来演示我是如何处理上述问题的。它们是我为了更好地理解命名管道而编写的两个程序。所有错误情况都会得到处理。有两个必须单独编译的可执行文件。在同一台PC上的两个独立终端中运行每个可执行文件。运行它们的顺序并不重要。无论哪一个先运行,都将创建命名管道,而另一个在启动时将注意到它已经创建(mkfifo错误处理)。写入器每秒向管道写入一次,每当read()返回时,读取器就从管道读取。在写入方,SIGPIPE被忽略,而EPIPE被处理。在两个终端窗口(阅读器或写入器)中的任何一个窗口中,按键盘上的'q‘,两个窗口都将退出。

如果没有忽略SIGPIPE,那么当我在写入器之前退出读取器(通过在读取器的终端中按Q)时,write()将失败,并触发SIGPIPE信号被写入器应用程序接收。这样做的默认行为是立即退出应用程序。当然,这不是我在将要使用此代码的多线程应用程序中所需要的。所以我忽略了这个信号,检查了errno,并进行了适当的处理。

编写器。c:

代码语言:javascript
复制
#include <stdio.h>      //for printf()
#include <stdlib.h>     //for malloc()
#include <stdint.h>     //for definitions of uint8_t etc..
#include <unistd.h>     //for sleep()
#include <sys/stat.h>   //for S_IRUSR, S_IWUSR, mkfifo()
#include <fcntl.h>      //for O_WRONLY
#include <errno.h>      //for errno, perror()
#include "kbhit.h"
#include <sys/types.h>
#include <signal.h>     //for signal()

/* Named pipe considerations (http://www.unixguide.net/unix/programming/2.10.3.shtml):
 *
 * To use the pipe, you open it like a normal file, and use read()
 * and write() just as though it was a plain pipe.
 * However, the open() of the pipe may block. The following rules apply:
 *
 * If you open for both reading and writing (O_RDWR), then the open will not block.
 *
 * If you open for reading (O_RDONLY), the open will block until
 * another process opens the FIFO for writing, unless O_NONBLOCK is
 * specified, in which case the open succeeds.
 *
 * If you open for writing O_WRONLY, the open will block until
 * another process opens the FIFO for reading, unless O_NONBLOCK is
 * specified, in which case the open fails.
 *
 * When reading and writing the FIFO, the same considerations apply as for
 * regular pipes and sockets, i.e. read() will return EOF when all
 * writers have closed, and write() will raise SIGPIPE when
 * there are no readers. If SIGPIPE is blocked or ignored, the call
 * fails with EPIPE.
 *
 */


static const char file_path[] = "/tmp/anurag";
static const char message[] = "Hello from writer!";

int main(void) {
    int ret;
    int fd=0;
    char keypress=0;

    /*
     * (http://stackoverflow.com/questions/4351989/cleanup-in-sigpipe)
     * EPIPE is returned if fd is connected to a pipe or socket whose reading end is closed.
     * When this happens the writing process will also receive a SIGPIPE signal.
     * (Thus, the write return value is seen only if the program catches, blocks or ignores this signal.)
     */
    signal(SIGPIPE, SIG_IGN);

    //Create the FIFO (named pipe)
    ret = mkfifo(file_path, S_IRUSR | S_IWUSR);

    if(ret == 0) {
        printf("mkfifo(): Named pipe created.\n");
    } else {
        if ((ret == -1) && (errno == EEXIST)) {
            perror("mkfifo()");
        } else {
            perror("mkfifo()");
        }
    }
    printf("Will now begin waiting on open()...\n");
    fd = open(file_path, O_WRONLY);
    if(fd == -1) {
        perror("open()");
    } else if (fd > 0) {
        printf("open(): Named pipe file descriptor opened for writing.\n");
    }


    while(keypress != 'q') {
        if (kbhit()) {
            keypress = getchar();
            printf("Exiting...\n");
        } else {
            ret = write(fd, message, sizeof(message));
            if(ret > 0) {
                printf("write(): %d bytes to pipe: %s\n",ret,message);
            } else if (ret <=0) {
                if(errno == EPIPE) {
                    printf("write(): got EPIPE, reader closed the pipe, exiting...\n");
                    break;
                } else {
                    perror("write()");
                    break;
                }
            }
        }
        sleep(1);
    };

    ret = close(fd);
    if(ret == 0) {
        printf("close(): Named pipe file descriptor closed.\n");
    } else {
        perror("close()");
    }

    ret = remove(file_path);
    if(ret == 0) {
        printf("remove(): Named pipe deleted.\n");
    } else {
        perror("remove()");
    }
    fflush(stdout);
    fflush(stderr);
    return EXIT_SUCCESS;
}

阅读器。c:

代码语言:javascript
复制
#include <stdio.h>      //for printf()
#include <stdlib.h>     //for malloc()
#include <stdint.h>     //for definitions of uint8_t etc..
#include <unistd.h>     //for sleep()
#include <sys/stat.h>   //for S_IRUSR, S_IWUSR, mkfifo()
#include <fcntl.h>      //for O_WRONLY
#include <errno.h>      //for errno, perror()
#include <string.h>     //for memset()
#include "kbhit.h"

/* Named pipe considerations (http://www.unixguide.net/unix/programming/2.10.3.shtml):
 *
 * To use the pipe, you open it like a normal file, and use read()
 * and write() just as though it was a plain pipe.
 * However, the open() of the pipe may block. The following rules apply:
 *
 * If you open for both reading and writing (O_RDWR), then the open will not block.
 *
 * If you open for reading (O_RDONLY), the open will block until
 * another process opens the FIFO for writing, unless O_NONBLOCK is
 * specified, in which case the open succeeds.
 *
 * If you open for writing O_WRONLY, the open will block until
 * another process opens the FIFO for reading, unless O_NONBLOCK is
 * specified, in which case the open fails.
 *
 * When reading and writing the FIFO, the same considerations apply as for
 * regular pipes and sockets, i.e. read() will return EOF when all
 * writers have closed, and write() will raise SIGPIPE when
 * there are no readers. If SIGPIPE is blocked or ignored, the call
 * fails with EPIPE.
 *
 */


static const char file_path[] = "/tmp/anurag";
static char message[100] = {0};

int main(void) {
    int ret;
    int fd=0;
    char keypress=0;
    //Create the FIFO (named pipe)
    ret = mkfifo(file_path, S_IRUSR | S_IWUSR);

    if(ret == 0) {
        printf("mkfifo(): Named pipe created.\n");
    } else {
        if ((ret == -1) && (errno == EEXIST)) {
            perror("mkfifo()");
        } else {
            perror("mkfifo()");
        }
    }
    printf("Will now begin waiting on open()...\n");
    fd = open(file_path, O_RDONLY);
    if(fd == -1) {
        perror("open()");
    } else if (fd > 0) {
        printf("open(): Named pipe file descriptor opened for reading.\n");
    }


    while(keypress != 'q') {
        if (kbhit()) {
            keypress = getchar();
            printf("Exiting...\n");
        } else {
            memset(message,0,100);
            ret = read(fd, message, 100);
            if(ret > 0) {
                printf("read(): %d bytes from pipe: %s\n",ret, message);
            } else if (ret == 0){
                printf("read(): got EOF, writer closed the pipe, exiting...\n");
                break;
            } else if (ret < 0){
                perror("read()");
                break;
            }
        }
        sleep(1);
    };

    ret = close(fd);
    if(ret == 0) {
        printf("close(): Named pipe file descriptor closed.\n");
    } else {
        perror("close()");
    }

    ret = remove(file_path);
    if(ret == 0) {
        printf("remove(): Named pipe deleted.\n");
    } else {
        perror("remove()");
    }
    fflush(stdout);
    fflush(stderr);
    return EXIT_SUCCESS;
}

上面的两个c文件都使用kbhit()来轮询从键盘接收到的字符。下面是实现该功能的代码:

kbhit.c:

代码语言:javascript
复制
//Taken from: http://cboard.cprogramming.com/c-programming/63166-kbhit-linux.html

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include "kbhit.h"

int kbhit(void) {
    struct termios oldt, newt;
    int ch;
    int oldf;

    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
    fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

    ch = getchar();

    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    fcntl(STDIN_FILENO, F_SETFL, oldf);

    if (ch != EOF) {
        ungetc(ch, stdin);
        return 1;
    }

    return 0;
}

kbhit.h:

代码语言:javascript
复制
#ifndef KBHIT_H_
#define KBHIT_H_

//Console related variables and functions
int kbhit(void);

#endif /* KBHIT_H_ */
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4351989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档