Wednesday, July 21, 2004

Shell script exit code

I just checked with few resources and could come up
with this.

> *man system *:
>
> The value returned is -1 on error (e.g. fork failed), and the
> return
> status of the command otherwise. This latter return status is
> in the
> format specified in wait(2). Thus, the exit code of the
> command will
> be WEXITSTATUS(status). In case /bin/sh could not be
> executed, the
> exit status will be that of a command that does exit(127).
>

>
> The return status of *wait(2) *consists of 2 parts, packed into a
> single 16 bit unsigned integer.
> a) a Signal Status that indicates why process terminated.
> b) the process termination value as returned by main or given to exit.
>
> So exit 1 in the script, which executed normally, *might* be a) 0x00
> b) as 0x01
> 0000 0001 0000 0000 which is 256
> exit 2 will be like 0000 0010 0000 0000 which is 512
> etc...
>
> So, the System call in the C Program is giving us the returnstatus of
> wait(2) for the script executed.
>
> But as the manual says, the exit code of the command will be
> WEXITSTATUS(status).
>
> So,
> #include
>
> int retcode = WEXITSTATUS(system(cmdline));
>
> gives the values returned by exit in the script.
> Regards,
> Senthil


>
>> If I write a c program which calls a shell script, I'm noticing that
>> the return code is a multiple of 256. Any idea why?
>>
>> #include
>> int main ()
>> {
>> char cmdline[50] = "source myscript.sh";
>> int retcode = system(cmdline);
>> printf("Returned %d\n", retcode);
>> return 0;
>> }
>>
>> #!/bin/bash
>> exit 0 --> returns 0 in the c code
>>
>> #!/bin/bash
>> exit 1 --> returns 256 in the c code
>>
>> #!/bin/bash
>> exit 2 --> returns 512 in the c code
>>
>> #!/bin/bash
>> exit 13 --> returns 3328 in the c code
>>
>>
>>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

No comments: