LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Using unsafe stdio.h functions in handlers (https://www.linuxquestions.org/questions/programming-9/using-unsafe-stdio-h-functions-in-handlers-4175590634/)

BruceV 10-02-2016 11:43 PM

Using unsafe stdio.h functions in handlers
 
See update at end...

Hello, I’m creating a program under Debian that uses Posix timers. Here’s the relevant pseudocode:

/* Handler, triggered on posix timer timeout. Has to include a write statement that sends up to 20 bytes to a serial port on every pass. */

static void handler (….)
{
……..
write (fd, buf, nvalues); // UNSAFE!!
}

Int main()
{
/* Set up posix timer & associated signal handling(typically 0.5 seconds repeat rate).
The program closely follows the example in Kerrisk: Linux programming interface”, ch23, pg500. */

// 'Sleep' loop, waiting for timer signals.
for ( ; ; )
{
pause() ;
}
}

The write statement is not handler-safe, neither is printf(), which I’ve tried to use for debugging. What’s happening is that the serial port write, and debug printf, statements, behave erratically, sometimes they work and sometimes they don’t.

I’ve tested the handler code by running it in a simple sleep() loop in main(), without problems. So aside from the unsafe functions, there appear to be no problems with it. I've also replaced the handler code with a single, simple printf statement, and that works OK (the Kerrisk sample code does the same thing).

How does one invoke write and printf safely from handlers?

Incidentally, I’m using posix timers because I need better timing accuracy than ordinary timer objects.

Also, please note that the the website is removing my line indents.

UPDATE (1 hour later)
A very slight recode within the handler, which should have had no effect, has caused the problem to go away. However, I aren't confident that the situation is solved, and would appreciate any advice to make the situation completely sound.

SECOND UPDATE: Found a website that looks promising. Shouldn't need any further attention.

ntubski 10-03-2016 04:15 PM

Quote:

Originally Posted by BruceV (Post 5612989)
Also, please note that the the website is removing my line indents.

Use [code][/code] tags to preserve indentation.

jpollard 10-03-2016 05:53 PM

It depends on what you mean by "sometimes they work and sometimes they don’t".

One thing to note - some system calls can be interrupted (the error return is EINTR). If this happens you are supposed to try the syscall again. For library control, you can always have a configuration option...


All times are GMT -5. The time now is 11:28 PM.