简体   繁体   English

普通函数调用和signal()系统调用有什么区别?

[英]What is the difference between normal function call and signal() system call?

While learning signal() system call, I supposed to come across the following code, 在学习signal()系统调用时,我应该遇到以下代码,

#include <stdio.h>
#include <signal.h>
void sigproc(int);
void quitproc(int);

int main(int argc,char **argv)
{
 signal(SIGINT, sigproc); //Is it like a normal Call to signal()?
 signal(SIGQUIT, quitproc);// This too?
 printf("ctrl- c disabled use ctrl\ to quit \n");
 while(1);
 return 0;
}

void sigproc(int signo)
{
printf("you have pressed ctrl - c \n");
}

void quitproc(int signo)
{
  printf("U cant quit\n");
//  exit(0);
}

I am calling the function signal() twice in main(). 我在main()中调用函数signal()两次。 But its executed only when I'm pressing Ctrl-C and Ctrl-\\ keys. 但它只在我按下Ctrl-C和Ctrl- \\键时执行。 I thought its also like normal function call. 我认为它也像正常的函数调用。 What is actually happening in the signal handler functions? 信号处理函数实际发生了什么?

The signal function establishes a signal handler. signal功能建立信号处理程序。 What it means: " When my process receives this signal, run this function instead of doing whatever the default was ". 意思是:“ 当我的进程收到此信号时,运行此函数而不是执行默认值 ”。

So, in your example the calls to signal don't call the function . 因此,在您的示例中,对signal的调用不会调用该函数 To actually see the signals in action, do this: 要实际查看运行中的信号,请执行以下操作:

  • Start your process in one terminal 在一个终端中启动您的流程
  • From another terminal: 从另一个终端:

     kill -INT `pidof proc` 

As a side note, printf and friends aren't async-signal-safe. 作为旁注, printf和朋友不是异步信号安全的。 It might come as a shocker, but it's unsafe to use them in signal handlers . 它可能会令人震惊,但在信号处理程序中使用它们并不安全


As a side side note, even if you tagged your question Unix it's important to know that signals (and the signal function) are standard, integral parts of C. Signal handling and the signal function are described in C99 in §7.14.1. 作为旁注,即使你标记了你的问题Unix ,重要的是要知道信号(和signal函数)是标准的,C的整体部分。信号处理和signal函数在§7.14.1中的C99中描述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM