先决条件: C信号处理
在本文中,子进程和父进程之间的通信是使用kill()和signal(),fork()系统调用完成的。
- fork()从父级创建子级进程。可以检查pid以确定它是子进程(如果pid == 0)还是父进程(pid =子进程ID)。
- 然后,父级可以使用pid和kill()将消息发送给子级。
- 孩子用signal()拾取这些信号并调用适当的函数。
2个进程如何使用kill()和signal()相互交谈的示例:
// C program to implement sighup(), sigint()
// and sigquit() signal functions
#include
#include
#include
#include
#include
// function declaration
void sighup();
void sigint();
void sigquit();
// driver code
void main()
{
int pid;
/* get child process */
if ((pid = fork()) < 0) {
perror("fork");
exit(1);
}
if (pid == 0) { /* child */
signal(SIGHUP, sighup);
signal(SIGINT, sigint);
signal(SIGQUIT, sigquit);
for (;;)
; /* loop for ever */
}
else /* parent */
{ /* pid hold id of child */
printf("\nPARENT: sending SIGHUP\n\n");
kill(pid, SIGHUP);
sleep(3); /* pause for 3 secs */
printf("\nPARENT: sending SIGINT\n\n");
kill(pid, SIGINT);
sleep(3); /* pause for 3 secs */
printf("\nPARENT: sending SIGQUIT\n\n");
kill(pid, SIGQUIT);
sleep(3);
}
}
// sighup() function definition
void sighup()
{
signal(SIGHUP, sighup); /* reset signal */
printf("CHILD: I have received a SIGHUP\n");
}
// sigint() function definition
void sigint()
{
signal(SIGINT, sigint); /* reset signal */
printf("CHILD: I have received a SIGINT\n");
}
// sigquit() function definition
void sigquit()
{
printf("My DADDY has Killed me!!!\n");
exit(0);
}
输出:
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。