Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this exit function add two zeros at the end in C?

Tags:

c

fork

exit

Hey so i made a program for university in C and the child should exit with hex 0xAA but it also adds two zeros at the end? Why does it do that? Am i overseeing something?

pid_t cpid;
int status;
cpid = fork();
if (cpid==-1){
    return -1;
}
else if(cpid==0){
    pid_t pid_child = getpid();
    pid_t ppid_child = getppid();
    printf("ChildProcessID from Child: %d\n",pid_child);
    printf("ParentProcessID from Child: %d\n",ppid_child);
    exit(0xAA);
}
else{
    printf("ChildProcessID: %d\n",cpid);
    wait(&status);
    printf("Exit Status Child: %#X\n",status);
}

at the end where it should output

Exit Status Child: 0XAA

it puts out

Exit Status Child: 0XAA00

I am sorry if anything is formatted wrongly or forgot anything. This is my first post on here. Thanks in advance.

like image 698
Johorn96 Avatar asked Dec 21 '25 22:12

Johorn96


1 Answers

When wait returns, the given parameter contains additional information besides just the exit code. It also tells you whether or not the process terminated normally.

There are macros you can use to extract the relevant parts:

wait(&status);
if (WIFEXITED(status)) {
    printf("Exit Status Child: %#X\n",WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
    printf("Child exited abnormally via signal %d\n", WTERMSIG(status));
} else {
    printf("Something else happened\n");
}
like image 141
dbush Avatar answered Dec 24 '25 18:12

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!