two blocking operations in one process

81 views Asked by At

I have 2 simple jobs. 1st is reading from pipe. And 2nd is do some operations by timeout. The problem is to make it work in one process (I khow way to do it in 2 process but it is unsuitable for me..).

And there is some reasons to dont use cron. 2 jobs should be runned run asyncronically (non blocking to each other).

Any ideas?

#include<stdio.h>                                                                                                                                
#include<stdlib.h>

void someAnotherJob();

main(){
    printf ("Hello!\n");
    int c;
    FILE *file, *file2;

    file = fopen("/dev/ttyUSB0", "r");
    file2 = fopen("out.txt", "a");

    if (file) {
        while ((c = getc(file)) != EOF){
            fputc(c, file2);
            fflush(file2);
        }
        fclose(file);
    }


    while (1) {
        someAnotherJob();
        sleep(10);
    }

}

void someAnotherJob()
{
    printf("Yii\n");
}
1

There are 1 answers

0
4pie0 On BEST ANSWER

You can use select to do nonblocking I/O from many descriptors:

fd_set rfds;
FD_ZERO(&rfds);
FILE* files[2];

if( !( files[0] = fopen( "/dev/ttyUSB0", "r"))
    // error

if( !( files[1] = fopen( "out.txt", "a"))
    // error

// for each file successfully opened
FD_SET( fileno( files[i]), &rfds);

int returned = select( highfd + 1, &rfds, NULL, NULL, NULL);

if ( returned) {
    // for each file successfully opened
        if ( FD_ISSET( fileno( files[i]), &rfds)) {
            // read
            printf( "descriptor %d ready to read", i);
        }
    }
}