C语言 父进程kill()子进程,但不响应read()或printf()?

vmpqdwk3  于 2023-04-19  发布在  其他
关注(0)|答案(1)|浏览(137)

当执行程序a的子进程被发送信号SIGTERM时,它应该在终止之前输出到标准输出。但是我的read()in(signal == 1)正在运行?我没有从printf函数得到任何输出。当信号被发送时,父进程似乎刚刚完成?
当“a”程序被发送到输入或者当它通过刷新和信号处理被终止时,它将打印到stdout put。

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);
        printf("NOTHING IS PRINTING HERE\n");
        

    }
}
xytpbqjk

xytpbqjk1#

你希望execlp调用在执行结束/中断时返回一个值,但这不会发生。
关于execlp documentation
对execlp的成功调用没有返回值,因为新进程映像覆盖了调用进程映像。但是,如果对execlp的调用不成功,则返回-1。
简单地说,如果程序运行,execlp将不会返回。

相关问题