0

パイプを使用して基本的な 2 人のチャット プログラムを作成しようとしています。パイプのもう一方の端に接続されているアプリケーションが強制的に閉じられると、以下のコードは無限ループに入ります。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;
}

私の出力:

出力

アプリケーションの強制終了時にアプリケーションが確実に終了するようにするにはどうすればよいですか?

4

1 に答える 1

1

read()あなたのプログラムはとの戻り値をチェックしませんwrite()

失敗した読み取りはbuf文字列「exit」で満たされないため、ブレーク条件は発生しません。

于 2013-09-01T16:00:09.380 に答える