SIGTSTP Handler终止父进程和子进程

问题描述 投票:2回答:1

我的目标:我有一个简单的c程序,它应该用我自己的程序覆盖默认的SIGTSTP处理程序,并仅向子进程发送SIGTSTP。

我的问题:SIGTSTP处理程序中的kill调用会停止父进程,并退出我的程序(不仅仅是子进程)。我究竟做错了什么?

编辑:这个问题似乎只发生在我使用以下make命令编译和运行我的代码时:gcc -o program *.c -lreadline && ./program。似乎(make进程?)被终止,因为我的输出在ctrl-z上包含以下行:gcc -o sandbox *.c -lreadline && ./sandbox有没有办法让我的程序具有所需的功能并使用make?

我的代码:

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

int child;

void handler();

static void SIGTSTP_Handler()
{
  if (child != 0) {
    kill(child, SIGTSTP);
  }
}

int main(void)
{
  signal(SIGTSTP, SIGTSTP_Handler);

  child = fork();

  if (child == 0) {   
    setpgid(0, getpid());

    printf("CHILD's PID ::: [ %d ]\n", getpid());

    printf("CHILD's GROUP ::: %d\n", getpgrp());

    execlp("sleep", "sleep", "30", NULL);

  }
  else {
    setpgid(child, child);

    int status;

    printf("CHILD's PID (From Parent Perspective) ::: [ %d ]\n", child);

    printf("PARENT's PID ::: %d\n", getpid());

    printf("PARENT's GROUP ::: %d\n", getpgrp());

    waitpid(child, &status, WUNTRACED | WCONTINUED);
  }

  while (1);
}
c linux makefile fork
1个回答
0
投票

这个问题是因为我启动程序使用的make命令被ctrl-z终止了。要解决此问题,您可以:

旧问题制作命令:

gcc -o program *.c && ./program

潜在解决方案

(1)从make命令中删除&& ./program

(2)编译并运行程序而不使用make

如果您希望在SIGTSTP信号的情况下保持主程序运行,我不确定是否仍然使用make启动程序

© www.soinside.com 2019 - 2024. All rights reserved.