#Output using signals

1 messages · Page 1 of 1 (latest)

ruby heart
#
#include <stdio.h>
#include <unistd.h>
#include <signal.h>

int childpid;

void handler(int signum) {
    printf("A\n");
    kill(childpid,SIGCONT);
}

int main() {
    int waitReturnPid;
    signal(SIGCHLD, handler);

    childpid = fork();

    if (childpid == 0) {
        sleep(1);
        raise(SIGTSTP);
        printf("B\n");
    } else if (childpid > 0) {
        wait(NULL);
        printf("C\n");
    }
}

Why is the output here
B
A
C
shouldnt it be
A
B
C
? i really dont get it please someone explain

scarlet trenchBOT
# ruby heart ```c #include <stdio.h> #include <unistd.h> #include <signal.h> int childpid; ...

Detected code, here are some useful tools:

Formatted code
#include<stdio.h> #include<unistd.h> #include<signal.h> int childpid;
void handler(int signum) {
  printf("A\n");
  kill(childpid, SIGCONT);
}
int main() {
  int waitReturnPid;
  signal(SIGCHLD, handler);
  childpid = fork();
  if (childpid == 0) {
    sleep(1);
    raise(SIGTSTP);
    printf("B\n");
  }
  else if (childpid > 0) {
    wait(NULL);
    printf("C\n");
  }
}
#

<@&987246683568103514> please have a look, thanks.

scarlet trenchBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

ruby heart
#

like why does it send the signal first

#

"kill"

#

in handler function

solemn flax
#

it's a race conditon based on OS and it's scheduler

#

I ran your code and got ```
B
A
A
A
C

#

and then I ran your code somewhere else and got ```
A
A
B
A
C

#

If you want to get your desired output you'll need to do some synchronization between the parent and child (at least that's what I think from my very limited knowledge of C)

ruby heart