I write a small program like following:
1, firstly create a process waiting for keyboard input commands(via getchar()).
2, secondly create a thread in the process waiting on a message queue.

each time after the thread receive a message, it can handle the message but cannot print the log message(via printf) to screen . After I press "Enter" button, the log message will be displayed. why?

who meet such interesting issues before?

thanks in advance.

wwq

Recommended Answers

All 4 Replies

Are you writing a C application?

I wrote a little c code to test signal handler like following: I have a signal handler to capture the signal and print the signal name.
-----------------------------------------------

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


void sigroutine(int dunno)
{
	switch(dunno)
	{
		case 1:
			printf("Get a signal -- SIGHUP ");
			break;
		case 2:
			printf("Get a signal -- SIGINT ");
			break;
		case 3:
			printf("Get a signal -- SIGQUIT ");
			break;
	}
	return;
}
int main(int argc, char** argv)
{
	int c;
        printf("process id is %d ",getpid());
	signal(SIGHUP, sigroutine); /*set the signal handler.*/
	signal(SIGINT, sigroutine);
	signal(SIGQUIT, sigroutine);
	while(1)
	{
		c = getchar();
		printf("input %c",c);
	}
}

-------------------------------------------
then I run it in a shell window. Then I press Ctrl+C(sending SIGINT)
, however the sigroutine() doesn't output the message to screen until I press any key in the shell. It seems the sigroutine() is executed only after the getchar() in the main() is executed.

who can help explain it?

thanks in advance.

wwq

you stdout is likely line-buffered, meaning you should terminate the printf calls with a \n char OR fflush(stdout) after printing OR setbuf(stdout, NULL) before printing.

but what youre doing is wrong because youre not allowed to call stdio functions from signal handlers since they are not reentrant. like, the interrupted getchar() call may have left data structures in an indeterminate state, and your printf call in the siignal handler may then wrongly access them. solution: only write a flag (of type volatile sig_atomic_t) in a signal handler and let someone else check that flag and print the message. i nthis case the main() function

also, you should really use sigaction() without setting SA_RESETHAND because with just signal() some systems will deinstall your signal handler and reset the default signal action after the signal arrived the first time

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.