父进程 kill() 子进程但随后不响应 read() 或 printf()?

问题描述 投票:0回答:0

当执行程序 a 的子进程收到信号 SIGTERM 时,它应该在终止之前输出到标准输出。但是我的 read() in (signal == 1) 正在运行?我没有从 printf 函数中得到任何输出。信号发出来的时候,爸妈好像刚刚说完?

int pid, childpid;
int fd1[2], fd2[2];
pipe(fd1);
pipe(fd2);
input = 10;

for (int signal = 0; signal < 2; signal++) {
    input = input + 2;
    char str[20];

    if (signal == 0) {
        pid = fork();
        if (pid == -1) {
            printf("fork failed");
            exit(EXIT_FAILURE);
        }

        if (pid == 0) {
            //child process
            childpid = getpid();
            dup2(fd1[0], STDIN_FILENO);
            dup2(fd2[1], STDOUT_FILENO);
            close(fd1[0]);
            close(fd1[1]);
            close(fd2[0]);
            int err;
            if ((err = execlp("./a", "./a", NULL)) < 0) { printf("HELP"); }
        }
        else {
            close(fd1[0]);
            close(fd2[1]);
            write(fd1[1], &input, sizeof(input));
            sleep(2);
            int nbytes = read(fd2[0], str, sizeof(str));
            printf("%d\n", nbytes);
        }
    }
    
   
    if (signal == 1) {
        write(fd1[1], &input, sizeof(input));
        kill(childpid, SIGTERM);
        int nbytes = read(fd2[0], str, sizeof(str));
        printf("%d\n", nbytes);
        

    }
}
c pipe fork exec kill
© www.soinside.com 2019 - 2024. All rights reserved.