Question

I am trying to create a rudimentary 2 person chat program using pipes. The code below goes into infinite loop if an application connected to the other end of the pipe is forced closed. The second program is same the as this except the names of the pipes.

#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;
}

My output :

output

How do I ensure the application exits on force closing of the application?

Was it helpful?

Solution

Your program doesn't check the return for read() and write().

Since a failed read won't fill buf with the string "exit", your break condition never occurs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top