0

我有 2 份简单的工作。第一个是从管道读取。第二是通过超时做一些操作。问题是让它在一个过程中工作(我知道如何在两个过程中做到这一点,但它不适合我..)。

并且有一些理由不使用 cron。2 个作业应该异步运行(互不阻塞)。

有任何想法吗?

#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");
}
4

1 回答 1

1

您可以使用 select 从许多描述符中执行非阻塞 I/O:

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);
        }
    }
}
于 2014-11-19T09:43:07.927 回答