kangear 发表于 2013-01-16 14:36

如果写到管道时读进程已终止会产生SIGPIPE---怎么实现?

我在学习SIGPIPE时,按照描述就是:如果写到管道时读进程已终止会产生SIGPIPE。另外还有一个socket也会出这个信号,不过socket这个先不管了。我学习FIFO,就想实现“如果写到管道时读进程已终止会产生SIGPIPE”(注:APUE上写的)。
我实现代码如下:#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>

#define FIFO_SERVER "/tmp/myfifo"

void my_func(int sign_no)
{
        if(sign_no == SIGPIPE)
        {
                printf("Sorry Sir,I have get SIGPIPE\n");
        }
    else
      exit(1);
}

int main(int argc, char** argv)
{
        int fd;
        char w_buf;
        int nwrite;
       
        signal(SIGPIPE, my_func);
       
        if((mkfifo(FIFO_SERVER, O_CREAT|O_EXCL|O_RDWR)<0) && (errno!=EEXIST))
    {
                printf("Cant create fifioserver\n");
        }       
   
    //fd = creat(FIFO_SERVER,O_RDWR|O_NONBLOCK);
        fd = open(FIFO_SERVER, O_RDWR|O_NONBLOCK, 0);
        if(fd == -1)
        {
                perror("open");
                exit(1);
        }
       
       
        if(argc == 1)
        {
                printf("Please send something\n");
                exit(-1);
        }
        strcpy(w_buf, argv);
    while(1)
    {
      
      nwrite = write(fd, w_buf, 100);       
            if(nwrite == -1)
            {
                    if(errno == EAGAIN)
                            printf("The FIFO has not been read yet,Please try later\n");
            }
            else
            {
                    printf("Write %s to the FIFO\n", w_buf);
            }
      sleep(1);
    }
        close(fd);
        return 0;
}然后在另一个终端手动删掉/tmp/myfifo这个管道,但是却不行,没有出现SIGPIPE这个信号,谁能帮帮我呀。
页: [1]
查看完整版本: 如果写到管道时读进程已终止会产生SIGPIPE---怎么实现?