SIGSTOP 在 c 程序中不起作用 [英] SIGSTOP not working in c program

查看:54
本文介绍了SIGSTOP 在 c 程序中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 C 程序,其中父进程挂起子进程并在几秒钟后继续执行它.

I am trying to write a C program in which the parent process suspends the child process and after a few seconds continues executing it.

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

void sigstop(); 
void sigcont();
void sigquit();

int main()
{ 
   int pid; 
   if ((pid = fork()) < 0) {
        perror("fork");
        exit(1);
    }
    if (pid == 0)
     { /* child */
       signal(SIGSTOP,sigstop);
       signal(SIGCONT,sigcont);
       signal(SIGQUIT, sigquit);
       for(;;); /* loop for ever */
     }
     else {
        printf("\nPARENT: sending SIGSTOP to suspend the process\n\n");
        kill(pid, SIGSTOP);
        sleep(5);
        printf("\nPARENT: sending SIGCONT to continue the suspended process\n\n");
        kill(pid, SIGCONT);
        sleep(5);
        printf("killing child");
        kill(pid,SIGQUIT);
        sleep(5);
     }
}

void sigstop()
{  
   printf("CHILD: I've been suspended\n");
}

void sigcont()
{  
   printf("CHILD: I'm back\n");
}

void sigquit()
{ 
    printf("My DADDY has Killed me!!!\n");
    exit(0);
}

printfsigstop() 中永远不会被执行并且 sigquit()printf("killing child") 之前被调用;.这是如何发生的,我如何才能以正确的顺序获得输出?

printf inside sigstop() never gets executed and sigquit() gets called before printf("killing child");. How does this happen and how can I get output in proper order ?

推荐答案

如果你 阅读signal(7) 手册页你会看到

If you read the signal(7) manual page you will see that

信号SIGKILLSIGSTOP 不能被捕获、阻止或忽略.

The signals SIGKILL and SIGSTOP cannot be caught, blocked, or ignored.

你根本无法捕捉到那个信号.

You simply can not catch that signal.

最后一点,关于 "Killing child" 以错误的顺序打印很容易修复:在打印的字符串中添加一个尾随换行符.

The last bit, about "Killing child" get printed in the wrong order is very easy to fix: Add a trailing newline to the string you print.

这是因为输出到 stdout(这是 printf 写入的内容)默认是行缓冲.这意味着 stdout 的内部缓冲区在换行符上刷新(即实际写入终端).如果你没有换行符,那么当进程退出时缓冲区会被刷新,也就是在你退出子进程之后.

This is because output to stdout (which is what printf writes to) is by default line-buffered. This means that the internal buffer of stdout is flushed (i.e. actually written to the terminal) on a newline. If you don't have the newline, then the buffer will be flushed when the process exits, which is after you exit the child process.

这篇关于SIGSTOP 在 c 程序中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆