SIGTSTP Handler terminates both parent and child process

时间:2018-09-18 20:23:45

标签: c linux makefile fork

My Goal: I have a simple c program that should overwrite the default SIGTSTP handler with my own, and send a SIGTSTP only to the child process.

My Issue: The kill call within the SIGTSTP handler stops the parent process, and exits my program (not just the child). What am I doing wrong?

Edit: This problem seems to only happen when I compile and run my code using the following make command: gcc -o program *.c -lreadline && ./program. It seems (the make process?) is terminated because my output contains the following line upon ctrl-z: gcc -o sandbox *.c -lreadline && ./sandbox Is there a way to both get my program to have the desired functionality and use make?

My Code:

#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);
}

1 个答案:

答案 0 :(得分:0)

该问题是由于启动程序所使用的make命令被ctrl-z终止而引起的。要解决此问题,您可以:

旧有问题的制作命令:

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

潜在的解决方案:

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

(2)无需使用make即可编译并运行程序

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