Sunday, October 19, 2014

Unix Prog: Return Value of System

test.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
 #include<signal.h>  
   
 int main(int argc, char* argv[])  
 {  
  sleep(5);  
  return 88;  
 }  

system.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
   
 int main(int argc, char* argv[])  
 {  
  int status = system("./test.out");  
  printf("status code: %d\n", status);  
  exit(0);  
 }  

1. Execute from the shell
1) Run the test.out directly from the shell, the return value is one returned in test.c
2) Run the test.out, and interrupt it with Ctrl C. The return value is the one assigned by system when meeting with interrupt signal to terminate the process
 ubuntu@ip-172-31-23-227:~$ ./test.out  
 ubuntu@ip-172-31-23-227:~$ echo $?  
 88  
 ubuntu@ip-172-31-23-227:~$ ./test.out  
 ^C  
 ubuntu@ip-172-31-23-227:~$ echo $?  
 130  

2. Execute by the shell
Same as above
 ubuntu@ip-172-31-23-227:~$ echo $?  
 88  
 ubuntu@ip-172-31-23-227:~$ sh -c "./test.out"  
 ^C  
 ubuntu@ip-172-31-23-227:~$ echo $?  
 130  

3. Execute by system function
1) Run the system.out to run test.out with system function, and the value returned is not the one returned in test.c. Instead, it is the value returned by "shell", launched by system.
2) Run the system.out to run test.out with system function, and interrupt it in the middle. Then the value returned is not the one returned in test.c. Instead, it is the value returned by "shell", launched by system, and it is the value of 2(SIGINT number).
 ubuntu@ip-172-31-23-227:~$ ./system.out  
 status code: 22528  
 ubuntu@ip-172-31-23-227:~$ ./system.out  
 ^Cstatus code: 2  

No comments:

Post a Comment