The following code is the value of a parent-child process alternating print variable counter. Because after fork, the child process copies the stack of the parent process, the signal processing function, the signal screen word, and the following procedure will be divided according to the different initial values of the counter.
#include <stdio.h> #include <signal.h> #include <unistd.h> #include <stdlib.h> #include <
String.h> sigset_t Newset, Zeroset;
static int counter = 1;
static int sigflag = 0;
void Sig_handler (int signo) {if (Signo = = SIGUSR1 | | signo = SIGUSR2) {Sigflag = 1;
} void Tell_wait () {sigemptyset (&newset);
Sigemptyset (&zeroset);
Sigaddset (&newset, SIGUSR1);
Sigaddset (&newset, SIGUSR2);
struct sigaction action;
Action.sa_handler = Sig_handler;
Sigemptyset (&action.sa_mask);
action.sa_flags = 0;
if (Sigaction (SIGUSR1, &action, NULL) < 0) {printf ("sigaction error\n");
Exit (-1);
} if (Sigaction (SIGUSR2, &action, NULL) < 0) {printf ("sigaction error\n");
Exit (-1);
} if (Sigprocmask (Sig_block, &newset, NULL) < 0) {printf ("Sigprocmask error\n");
Exit (-1);
} void Tell_parent (pid_t pid) {Kill (PID, SIGUSR2);} void Wait_parent () {while (Sigflag = 0) {sigsuspend (&zerosET);
} sigflag = 0;
if (Sigprocmask (Sig_block, &newset, NULL) < 0) {printf ("Set Sigprocmask error\n");
Exit (-1);
} void Tell_child (pid_t pid) {Kill (PID, SIGUSR1);}
void Wait_child () {while (Sigflag = 0) {sigsuspend (&zeroset);
} sigflag = 0;
if (Sigprocmask (Sig_block, &newset, NULL) < 0) {printf ("Set Sigprocmask error\n");
Exit (-1);
int main (int argc, char **argv) {pid_t pid;
Tell_wait ();
if ((PID = fork ()) < 0) {perror ("fork");
return-1;
else if (PID = = 0)//child {counter = 0;
while (1) {wait_parent ();
counter+=2;
Char line[128] = {0};
sprintf (Line, "#========child:%d\n", counter);
Write (Stdout_fileno, line, strlen);
printf ("#========child:%d\n", counter);
Tell_parent (Getppid ());
} else {counter =-1;
while (1) {counter+=2;
Char line[128] = {0};
sprintf (Line, "#===parent:%d\n", counter);
Write (Stdout_fileno, line, strlen); //printf ("#===parent:%d\n", counter);
Tell_child (PID);
Wait_child ();
} waitpid (PID, NULL, 0);
return 0;
}
What needs to be noted is the printf part of the annotation, which does not appear when you use printf to redirect the output (./a.out >> test) to a file. The reason is that the redirected file is fully buffered and printf is buffered and buffered to a certain extent to output from the memory buffer to the file.