Reputation: 11921
Here is my code:
#include<stdio.h>
#include<signal.h>
void my_isr();
int main()
{
signal(SIGALRM,my_isr);
alarm(5);
pause();
printf("in main()...\n");//case2 comments it //case 1 & 3 uncomments it
return 0;//case 1 & 2 comments this line // case 3 uncomment it
}
void my_isr()
{
printf("I am in my_isr()\n");
}
If I am running process in background
Case 1 : If I didn't return 0
in main function at end of main scope, it( shell-bash) prints exit
value 13(no of printable characters in last printf). Why only last printf ? Is it undefined behaviour ?
xyz@xyz-PC:~/s_flow$ ./a.out &
[1] 9158
xyz@xyz-PC:~/s_flow$ I am in my_isr()
in main()...
[1]+ Exit 13 ./a.out
Then shell prints Exit
with status value 13
.
Case 2 : If there is no return 0
at the end of main() and I removed last printf
(which prints 13 characters)
xyz@xyz-PC:~/s_flow$ ./a.out &
[1] 9169
xyz@xyz-PC:~/s_flow$ I am in my_isr()
[1]+ Exit 255 ./a.out
Then shell prints Exit with status value as 255. How ?
case 3 : Finally If everything is provided correctly i.e If I mention return 0
at end of main() then shell print's Done
message with no value.
xyz@xyz-PC:~/s_flow$ ./a.out &
[1] 9178
xyz@xyz-PC:~/s_flow$ I am in my_isr()
in main()...
[1]+ Done ./a.out
I understood roughly why bash shell
prints Exit 13
, Exit 255
& Done
but any further explanation is welcome. my real question is how shell is interacting with OS when one process is running in background, where I can find these shell messages ? and how OS
returns these status value to shell
& then shell prints ? Any help appreciated. Thanks in advance.
Upvotes: 0
Views: 94
Reputation: 3360
The 13 is the result code of your program. It terminates with result code 13 in both cases - when it is run background and foreground as well. But when the program is running foreground then bash does not print the result code. But you can check that the result code is actually 13 for foreground run:
$ ./a.out
in isr() 16664:..
in isr() 16664:..
in main()...
$ echo $?
13
And why it is 13? Result code is normally the result code of the main()
function. But the main()
function does not contain any return statement so the result is architecture dependent. In this case the value 13 is the return value from the last printf
call because
printf("in main()...\n");
returns 13 what is the length of the printed string. And the value 13 remains in the register by chance.
Upvotes: 2
Reputation: 121387
The "random" exit code is due to the incorrect return type of main()
. main()
should return int
, which is the value returned to the calling environment.
When a background process completes, then the its associated terminal is notified of the completion with its exit status. But your program doesn't send its exit status correctly. This is technically undefined behaviour.
Upvotes: 2