C++ 强制关闭管道一端程序的怪异行为

C++ 强制关闭管道一端程序的怪异行为,c++,piping,C++,Piping,我正在尝试使用管道创建一个基本的2人聊天程序。如果连接到管道另一端的应用程序被强制关闭,下面的代码将进入无限循环。第二个程序与此相同,只是管道的名称不同 #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <stdio.h> #include <cstdlib> #include <pthread.h> #include <stri

我正在尝试使用管道创建一个基本的2人聊天程序。如果连接到管道另一端的应用程序被强制关闭,下面的代码将进入无限循环。第二个程序与此相同,只是管道的名称不同

#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <cstdlib>
#include <pthread.h>
#include <string.h>
#define MAX_BUF 1024
void *th()
{
    int fd;
    char myfifo[] = "/tmp/myfifo2", buf[MAX_BUF];
    fd = open(myfifo, O_RDONLY);
    while(buf=="");             
    while(1)
    {
        read(fd, buf, MAX_BUF);
        printf("Stranger : %s\n", buf);
        if(!strcmp(buf,"exit"))         
            break;  
        else buf[0]='\0';
    }
    close(fd);
    pthread_exit(NULL);
}
int main()
{
    int fd;
    char myfifo[] = "/tmp/myfifo", msg[25];
    pthread_t thread;
pthread_create(&thread, NULL, th, NULL); //error
    mkfifo(myfifo, 0666);
    fd = open(myfifo, O_WRONLY);
    while(msg!="exit")
    {
        printf("You : ");
        gets(msg);
        if(!strcmp(msg,"exit"))
            {write(fd, msg, sizeof(msg));  break;}
        else write(fd, msg, sizeof(msg));
    }
    close(fd);
    unlink(myfifo);
    return 0;
}
我的输出:


如何确保应用程序在强制关闭应用程序时退出?

您的程序不会检查
read()
write()
的返回


由于失败的读取不会用字符串“exit”填充
buf
,因此中断条件永远不会发生。

我发布了一个答案,忽略了
while(buf==“”)这一行我认为这是一个复制错误(同样,从来都不是真的)。所以关闭管道的一端不会禁用管道?因为
(!strcmp(buf,“exit”)|(!strcmp(buf,”)))
似乎有效。在每个循环结束时,您将
buf[0]='\0'
。由于
read()
没有更新缓冲区,因此它仍然是一个空字符串。为什么
pthread_create
会给我一个错误:
从“void*(*)()”到“void*(*)(void*)”
的转换无效。编译时,我必须使用
-fpermissive
。我不理解这个错误。因为你的函数签名不正确
pthread_create()
要求函数获取一个空指针并返回一个空指针,即
void*func(void*arg)
那么该怎么办呢?写
(void*)
,因为我不想通过?我不知道在这种情况下该怎么办。有关错误代码,请参见编辑。