How to interrupt a fread call?

后端 未结 6 1321
暗喜
暗喜 2021-01-18 13:19

I have the following situation:

There is a thread that reads from a device with a fread call. This call is blocking as long as there is no data send from the device.

6条回答
  •  旧时难觅i
    2021-01-18 13:30

    Signal handlers will not interrupt fread unless they were installed as interrupting, and unhandled signals are never interrupting. The POSIX standard allows handlers installed by the signal function to be wither interrupting or non-interrupting by default (and on Linux the default to non-interrupting), so if you need a specific behavior, use the sigaction function and specify the desired sa_flags. In particular, you need to omit the SA_RESTART flag. For example:

    struct sigaction sa = { .sa_handler = dummy_func, .sa_flags = 0 };
    sigaction(SIGUSR1, &sa, 0);
    

    Note that sa_flags would implicitly be 0 anyway if omitted, but I included it explicitly in the initializer to illustrate. Then you can interrupt the fread by sending SIGUSR1 with kill or pthread_kill.

提交回复
热议问题