Wednesday, January 6, 2010

How to Run and Get status of Script From C-code

Running is pretty easy by using system() call

ret=system("./amit.sh");
printf("status is %d \n",ret/256);

-------Script--------
1 #!/bin/bash
2 echo HI;
3 echo AMIT;
4 exit 15
------------------------
Output is 15

Why 256 is required to divide?
reason when we fork a child it return status in 2 bytes status can e checked by wait() in parent . if wait is not there it will be Zombie ?
now when child goes it returns status and semd SINGNAL SIGCHLD to parent
Status is return in two bytes 1st significant is for return value 2nd byte should have all Zero in success.
so if child is returning 3 it will be 00000011|00000000 to display it as 3 we need to right shift 8 times or devide by 256 same ......

The function exit(status) causes the executable to return "status" as the return code for main(). When exit(status) is called by a child process, it allows the parent process to examine the terminating status of the child (if it terminates first).

NOTE: exit() vs _exit(): The C library function exit() calls the kernel system call _exit() internally. The kernel system call _exit() will cause the kernel to close descriptors, free memory, and perform the kernel terminating process clean-up. The C library function exit() call will flush I/O buffers and perform aditional clean-up before calling _exit()

No comments: