Command clear won't take kill signal ( in infinite loop | c program ) - c

I used the command "clear" in C language at infinite loop just for test and the kill signal does not stop it.
Why the program does not stop when i press Ctrl + C ?
#include <stdlib.h>
int main () {
while (1) {
system("clear");
}
return 0;
}

Killing clear will not help, because the infinite loop is in your own program. Kill that.
ControlC is only useful if you can get the system to pay attention. It sounds as if your terminal is too busy writing to the screen to do this.
From another terminal, run top and kill your program (which likely is near the top of the screen).

You could include a signal handler to 'catch' your CRTL-C input (which is SIGINT below) and then exit. Hopefully, this stub code will give you the idea. If not, I can provide a complete working example but would like to see you try first. :-)
#include <signal.h>
...
void stop (int signal) {
exit;
}
int main() {
signal(SIGINT, stop);
...
}
HTH

Related

Raspberry Pi clean exit on CTRL+C in C

First of all, let me apologize as I can see that similar questions have been posted quite a few times in the past. However, as I am very unfamiliar with C, I need help confirming this.
I am trying to ensure that my program leaves a clean gpio if I interrupt it with CTRL+C. Easily done in python or java, but C proves to be a harder nut to crack for me, as I was led to believe that no try-catch-finally exists in C. Googling it, I found what I think may be the solution, but unexperienced as I am, I'm not sure it's done properly. Here is my code:
#include <stdio.h>
#include <wiringPi.h>
#include <signal.h>
void CleanGPIO() {
pinMode(1,INPUT);
}
int main()
{
wiringPiSetup();
signal(SIGINT, CleanGPIO);
pinMode(1, PWM_OUTPUT);
for (int i = 0; i < 1024; ++i) {
pwmWrite(1, i);
delay(1);
}
for (int i = 1023; i >= 0; --i) {
pwmWrite(1, i);
delay(1);
}
pinMode(1,INPUT);
return 0;
}
I have tested it and it works as intended (pin 1 is set as IN after I interrupt it with CTRL+C), but I'm concerned if this is the safe way to do it, and if there is a better solution available.
calling any function which is not speficied as signal-safe from a signal handler is undefined behaviour. I suppose there is no such guarantee about pinMode.
The proper way would be to set a volatile int flag that you periodically check in your main loop.
volatile int terminating = 0;
void terminate(int sign) {
signal(SIGINT, SIG_DFL);
terminating = 1;
}
int main() {
for (...) {
if (terminating) {
// cleanup
exit(1);
}
}
}
the call to signal inside the handler is to allow force terminating the program with a second ctrl+c in case proper clenup takes too long or is stuck for any reason.
Your solution is nearly right. You should also call exit in order to force the program to terminate (assuming you want to terminate immediately). The exit call takes a parameter which is the exit status to return to the caller (e.g., the shell). This should be non-zero for abnormal termination.
So, it should be:
void CleanGPIO() {
pinMode(1,INPUT);
exit(1);
}
If you don't want to exit from the handler but from main in a more controlled fashion you can set a flag instead and check the flag value inside the loops.

Why some function could reduce sleep(n) into sleep(0)?

I have a very strange problem in C. A function from a proprietary library reduces sleep(n) to sleep(0).
My code looks like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> /*sleep() */
int main(int argc, char** argv){
//...
AStreamEngine.init();
AStreamEngine.setCodec(3);
AStreamEngine.start(); //problematic function
printf("a");
sleep(100);
printf("b");
return 0;
}
If the problematic function is commented out, then printing "a" follows by printing "b" after 100 sec. But if isn't commented out, "ab" is printed. So the program ends very quickly and I cannot notice if the engine works.
I found that:
if I replace sleep() by getchar() the engine works correctly.
if I put active waiting by a for-loop then it also works.
Does anyone have any idea why happens? And how to fix (bypass) this feature/bug? I don't want use getchar and active waiting.
Update:
I don't have source of the library. I have only binary .so file.
Base on responces I add a below code add end:
struct timespec to_sleep = { 1, 0 };
int ret = nanosleep(&to_sleep,&to_sleep);
printf("%d\n",ret);
if(ret == -1){
printf(" break sleep : %d %s", errno,strerror(errno));
}
And I get output:
-1
break sleep : 4 Interrupted system callc
Now I try to bypass by thread.
"sleep" can be interrupted by signals - see http://man7.org/linux/man-pages/man3/sleep.3.html . My guess is that the "start" function started a thread which might have caused signals to be sent to your program. Put "sleep" in a loop like this:
unsigned int x = 100;
while (x > 0) { x = sleep (x); }
Another point: printf may be line-buffered. In that mode, the output is only seen if you print a "\n" character. Try using "a\n".
As rightly said by Jack, usleep and sleep can be interrupted by the delivery of signals (E.g presence of ioctl, read, write function calls).
One of the smart way to avoid this issue is to use nanosleep. Like sleep and usleep, nanosleep can also be interrupted by the delivery of signals but the difference is, its second argument tells you how much time is remaining.
You can use this argument to make sure your code sleeps for the specified amount of time. Replace your sleep and usleep function with a while loop containing nanosleep. Following is the example usage,
struct timespec to_sleep = { 1, 0 }; // Sleep for 1 second
while ((nanosleep(&to_sleep, &to_sleep) == -1) && (errno == EINTR));
Off course this solutions is not suitable for the application where exact amount sleep is required but it is very useful in the cases where minimum delay is required before executing next function.
After examination, I think that the using of the sleep() function is useless on your case.
Indeed, the sleep function uses the pause() function, which wait for a signal and stops if your process receive a signal call.
In your case it's probably the problem, and it explains why the sleep() function stops when you call the AStreamEngine.start() function.
I think that the best solution is to use the usleep() function, which should not stops if your process receive a signal.
Try this :
usleep(VALUE_IN_MILISECONDS);
Good luck ! :)

Why does my C program close early?

I am having a very confusing problem right now. I wrote a test program for myself, but sometimes after I input Crtl+C, which is what I assume to be the EOF, the program closes early without running through some more commands below the While Loop I wanted it to cancel from.
#include <stdio.h>
#include <string.h>
int main()
{
char message[140];
char* p = message;
int count;
int i = 0;
int charGT;
while((charGT=getchar()) != EOF)
{
message[i] = charGT;
i++;
printf("%d" , i);
}
printf("next");
count = strlen(p);
printf("%d", count);
printf("after");
return (0);
}
Inputting "asd\n^C" will cause my program to end early. "next" or "after" will not be printed
My theory is that somehow, the \n is causing the program to step out of the loop for a moment, and then Crtl+C is exiting the program, but I don't know how that would work.
Ctrl+C is the break command and will send an interrupt signal to your application. The default handler will cause this to exit the process.
Ctrl+D is the EOF command you are looking for.
For running on windows, to enter EOF press Ctrl+Z and then press ENTER. In UNIX systems it is Ctrl+D, in Windows Ctrl+Z.
When a program is running if you press Ctrl-c a signal is sent to abort the program and the program is aborted. However, if you want to use Ctrl-c as an input but not abort the program write one signal handler which catches the signal when you press Ctrl-c and perform the action you wanted to.

sleep function will abort when received a signal?

#include <signal.h>
#include <stdio.h>
void ints(int i )
{
printf("ints \n");
}
int main(void)
{
signal(SIGINT, ints);
sleep(10);
}
input Ctrl+C , the program will terminate immediately with output:
^ints
I was wondering why,in my opinion,the program should terminate after 10 seconds no matter how many times Ctrl+C is input.
sleep() is one of those functions that is never re-started when interrupted.
interestingly, it also does not return a EINT as one would expect.
It instead returns success with the time remaining to sleep.
See:
http://www.kernel.org/doc/man-pages/online/pages/man7/signal.7.html
for details on other APIs that do not restart when interrupted

Continue running program until user type Ctrl + a

I'm practicing C programming for Linux for an exam.
I don't know how to exit the program when user press Ctrl + a ( not Ctrl+c )
For example, looping something until user press Ctrl+a
Could anyone tell me how to check Ctrl+a input?
Notes: I'm using 'gcc' and run output with './a.out'
Thanks in advance for everyone!
Turbo C and other implementations of C for Windows had a function call getch() which would read single characters from the keyboard; those would have done what you want.
In POSIX environments, such as are implemented by gcc-compiled programs under Unix/Linux, that functionality isn't directly there.
There's a library called curses which allows C programs to do full-screen output processing, and there is also getch() functionality in curses. This may end up being the simplest answer to your problem. You'll need to read the documentation on curses and link the header files and library into your program.
There is special support for Ctrl-C, which is translated into a signal by the system. If you want your program to stop as soon as another specific key combination is used, it will be much harder.
you will need to check the standard input of your program, and you will need to set the standard input so the inputs are not buffered (otherwise you won't see any input until it is validated by the user pressing "return"). The latter part would be done with a ioctl() call and would not be portable;
you will need either threads or polling, none of which is very palatable in C.
There are more interesting things to practice in C than these.
catching ctrl-c event
This post answers your question
did you looking for something like this ???
this program won't be stopped since you hit ctrl+A and Enter.
#include <stdio.h>
int main() {
char a;
while( a!=1 ) //Ascii code for ctrl + A == 1
{
a=getchar();
printf("still looping ...\n");
}
printf( "HA! You pressed CTRL+A\n" );
return 0;
}
But if you wanna terminate your program just after pressing ctrl+A (without hitting enter after that), here you are:
#include <stdio.h>
#include <ncurses.h>
int main() {
char a;
initscr();
raw();
while( a!=1 )
a=getch();
endwin();
return 0;
}
for compiling second code using GCC, try this command:
gcc -o program.o -lncurses program.cpp
This will do what you want:
stty intr ^a
./a.out
For extra credit, do the equivalent of "stty intr ^a" using the appropriate library function, e.g. "man termios".
Someone posted first with following code which works for me but I don't know why he deleted his answer.
Original Link : http://www.c.happycodings.com/Gnu-Linux/code18.html
#include <stdio.h>
#include <unistd.h> /* sleep(1) */
#include <signal.h>
void ex_program(int sig);
int main(void) {
(void) signal(SIGINT, ex_program);
while(1)
printf("sleeping .. ZZZzzzz ....\n"), sleep(1);
return 0;
}
void ex_program(int sig) {
printf("Wake up call ... !!! - Catched signal: %d ... !!\n", sig);
(void) signal(SIGINT, SIG_DFL);
}
This is how to set CTRL-A as interrupt to break the process. Notice too that CTRL-C doesn't break it after tcsetattr is called.
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
struct termios termios;
if ( tcgetattr(0, &termios) != -1 ) {
termios.c_cc[VINTR] = '\x01'; /* CTRL-A */
if ( tcsetattr(0, 0, &termios) != -1 ) {
printf("Ready. Press CTRL-A to break this program\n");
while ( 1 ) {
printf("*\n");
sleep(1);
}
}
}
}

Resources