extra2

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <signal.h>

int pid1, pid2;


int main()
{
int fd[2];
char OutPipe[100], InPipe[100];
pipe(fd);
while ((pid1 = fork()) == -1);

if (pid1 == 0) {
lockf(fd[1], 1, 0); //Lock pipe
sprintf(OutPipe, "\nChild process 1 is sending message!\n");
write(fd[1], OutPipe, 50); //Write content
sleep(5); //Await read process to read.
lockf(fd[1], 0, 0); //Unlock pipe
exit(0);
}
else {
while ((pid2 = fork()) == -1);
if (pid2 == 0) {
lockf(fd[1], 1, 0);
sprintf(OutPipe, "\nChild process 2 is sending message!\n");
write(fd[1], OutPipe, 50);
sleep(5);
lockf(fd[1], 0, 0);
exit(0);
}
else {
wait(0); //Await child pro1 to end.
read(fd[0], InPipe, 50);
printf("%s\n", InPipe);
wait(0); //Await child pro2 to end.
read(fd[0], InPipe, 50);
printf("%s\n", InPipe);
exit(0);
}
}

}

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>

int wait_flag;
void stop();


int main()
{
int pid1, pid2;
signal(3, stop);
while ((pid1 = fork()) == -1);

if (pid1 > 0) {
while ((pid2 = fork()) == - 1);
if (pid2 > 0) {
wait_flag = 1;
sleep(5);
kill(pid1, 16);
kill(pid2, 17);
wait(0); //Await the signal that indicate pid1 has been killed.
wait(0); //Await the signal that indicate pid2 has been killed.
printf("\nParent process is killed !!\n");
exit(0);
}
else {
wait_flag = 1;
signal(17, stop); //Await signal 17.
printf("\nChild process 2 is killed by parent!!\n");
exit(0);
}
}
else {
wait_flag = 1;
signal(16, stop); //Await signal 16
printf("\nChild process 1 is killed by parent!!\n");
exit(0);
}
return 0;
}

void stop() {
wait_flag = 0;
}

猜你喜欢

转载自www.cnblogs.com/jspr-c/p/9243409.html